Inheritance: ImageTransition
Exemple #1
0
        private static WpfSize ComputeScaleFactor (Size availableSize, Size contentSize, Stretch stretch, StretchDirection stretchDirection)
        {
            bool isWidthInfinite = availableSize.IsWidthInfinite;
            bool isHeightInfinite = availableSize.IsHeightInfinite;

            if (stretch == Stretch.None || (isWidthInfinite && isHeightInfinite))
                return new WpfSize(1, 1);

            double scaleX = contentSize.Width == 0 ? 0 : (double)availableSize.Width / contentSize.Width;
            double scaleY = contentSize.Height == 0 ? 0 : (double)availableSize.Height / contentSize.Height;

            if (isWidthInfinite)
                scaleX = scaleY;
            else if (isHeightInfinite)
                scaleY = scaleX;
            else if (stretch == Stretch.Uniform)
                scaleX = scaleY = Math.Min(scaleX, scaleY);
            else if (stretch == Stretch.UniformToFill)
                scaleX = scaleY = Math.Max(scaleX, scaleY);

            Func<double, double, double> clip = null;
            if (stretchDirection == StretchDirection.UpOnly)
                clip = Math.Max;
            else if (stretchDirection == StretchDirection.DownOnly)
                clip = Math.Min;
            if (clip != null) {
                scaleX = clip(scaleX, 1);
                scaleY = clip(scaleY, 1);
            }

            return new WpfSize(scaleX, scaleY);
        }
Exemple #2
0
		public static void SetStretch(ImageBrush brush, Stretch stretch)
		{
			if (brush == null)
				return;

			brush.Stretch = stretch;
		}
		public static void UpdateImageSource(FrameworkElement content, Grid hostBody, ImageSource imageSource, Stretch stretch)
		{
			if (hostBody == null || content == null)
				return;

			var imgRects = hostBody.Children.OfType<Rectangle>().ToArray();

			for (int i = imgRects.Count() - 1; i >= 0; i--)
			{
				hostBody.Children.Remove(imgRects[i]);
			}

			if (imageSource == null)
				return;

			var imgBrush = new ImageBrush { ImageSource = imageSource, Stretch = stretch };
			var imgRect = new Rectangle
			{
				OpacityMask = imgBrush
			};

			hostBody.Children.Add(imgRect);

			ApplyForegroundToFillBinding(content, imgRect);

			//var sb = new Storyboard();
			//ControlHelper.CreateDoubleAnimations(sb, imgBrush, "Opacity", 0.2, 1, 75);
			//hostBody.Dispatcher.BeginInvoke(sb.Begin);
		}
 protected GridImageBase(int width, int nrRows, int nrColumns, List<BitmapSource> images, 
     Color backgroundColor, Color fontColor, Stretch stretch = Stretch.UniformToFill)
 {           
     NrRows = nrRows;
     NrColumns = nrColumns;
                                       
     Images = images;
     Stretch = stretch;
     BackgroundColor = backgroundColor;
     FontColor = fontColor;
 }
Exemple #5
0
		static Size ComputeScaleFactor (Size availableSize, Size contentSize, Stretch stretch, StretchDirection stretchDirection)
		{
			double widthFactor = 1.0;
			double heightFactor = 1.0;
			bool widthSet = !double.IsPositiveInfinity (availableSize.Width);
			bool heightSet = !double.IsPositiveInfinity (availableSize.Height);
			if ((stretch == Stretch.Uniform || stretch == Stretch.UniformToFill || stretch == Stretch.Fill) && (widthSet || heightSet))
			{
				widthFactor = (IsZero (contentSize.Width) ? 0.0 : (availableSize.Width / contentSize.Width));
				heightFactor = (IsZero (contentSize.Height) ? 0.0 : (availableSize.Height / contentSize.Height));
				if (!widthSet)
					widthFactor = heightFactor;
				else
				{
					if (!heightSet)
						heightFactor = widthFactor;
					else
					{
						switch (stretch)
						{
						case Stretch.Uniform:
							{
								double num3 = (widthFactor < heightFactor) ? widthFactor : heightFactor;
								heightFactor = (widthFactor = num3);
								break;
							}
						case Stretch.UniformToFill:
							{
								double num4 = (widthFactor > heightFactor) ? widthFactor : heightFactor;
								heightFactor = (widthFactor = num4);
								break;
							}
						}
					}
				}
				switch (stretchDirection)
				{
				case StretchDirection.UpOnly:
					if (widthFactor < 1.0)
						widthFactor = 1.0;
					if (heightFactor < 1.0)
						heightFactor = 1.0;
					break;
				case StretchDirection.DownOnly:
					if (widthFactor > 1.0)
						widthFactor = 1.0;
					if (heightFactor > 1.0)
						heightFactor = 1.0;
					break;
				}
			}
			return new Size (widthFactor, heightFactor);
		}
        /// <summary>
        /// Initializes a new instance of the XHtmlImage class.
        /// </summary>
        public XHtmlImage(XHtmlPage page)
        {
            Page = page;

            horizontalAlignment = HorizontalAlignment.Left;
            verticalAlignment = VerticalAlignment.Top;
            SnapsToDevicePixels = true;
            stretch = Stretch.None;

            //IsEnabledChanged += (sender, e) => Opacity = (bool)e.NewValue ? 1 : 0.4;
            //SizeChanged += (sender, e) => SetStretch(); // pour mettre à jour le stretch au redimensionnement
        }
Exemple #7
0
		public void AddImage(string path, TileMode tile = TileMode.None, Rect? targetArea = null, Stretch stretch = Stretch.Fill, Rectangle rect = null, UriKind kind = UriKind.Relative)
		{
			BitmapImage bm = new BitmapImage(new Uri(path, kind));
			UIElement el = null;
			if (tile != TileMode.None && rect == null)
			{
				Rectangle r = new Rectangle();
				if (targetArea.HasValue)
				{
					r.Width = targetArea.Value.Width;
					r.Height = targetArea.Value.Height;
				}
				else
				{
					r.Width = this.ActualWidth;
					r.Height = this.ActualHeight;
				}
				Rect rr = new Rect();
				rr.Width = bm.PixelWidth;
				rr.Height = bm.PixelHeight;
				ImageDrawing d = new ImageDrawing(bm, rr);
				DrawingBrush brush = new DrawingBrush(d);
				brush.Viewport = rr;
				brush.ViewportUnits = BrushMappingMode.Absolute;
				brush.TileMode = tile;
				brush.Stretch = Stretch.Fill;
				r.Fill = brush;
				el = r;
			}
			else
			{
				Image img = new Image();
				img.Width = bm.Width;
				img.Height = bm.Height;
				img.Source = bm;
				el = img;
			}
			RenderCanvas.Children.Add(el);
			if (targetArea.HasValue)
			{
				Canvas.SetLeft(el, targetArea.Value.X);
				Canvas.SetTop(el, targetArea.Value.Y);
			}
			else
			{
				Canvas.SetLeft(el, 0);
				Canvas.SetTop(el, 0);
			}
		}
		/// <summary>
		/// Apply the current text settings to the values
		/// </summary>
		/// <param name="values">values array to be used</param>
		/// <returns>Array of strings from the values using the current settings</returns>
		public string[] Apply(byte[,] values)
		{
			if (values == null)
			{
				return null;
			}

			// only apply brightness and contrast if necessary
			if (Brightness != 0 || Contrast != 0)
			{
				BrightnessContrast filter = new BrightnessContrast(IsBlackTextOnWhite ? Brightness : -Brightness,
					IsBlackTextOnWhite ? Contrast : -Contrast);

				values = filter.Apply(values);
			}

			if (Stretch)
			{
				Stretch filter = new Stretch();
				values = filter.Apply(values);
			}

			if (Levels.Minimum != 0 || Levels.Maximum != 255 || Levels.Median != 0.5f)
			{
				//values = AscgenConverter.ApplyLevels(values, Levels.Minimum, Levels.Maximum, Levels.Median);

				Levels filter = new Levels(Levels.Minimum, Levels.Maximum, Levels.Median);
				values = filter.Apply(values);
			}

			if (Sharpen)
			{
				values = AsciiConverter.SharpenValues(values);
			}

			if (Unsharp)
			{
				values = AsciiConverter.UnsharpMaskValues(values, 3);
			}

			if (FlipHorizontally || FlipVertically)
			{
				Flip filter = new Flip(FlipHorizontally, FlipVertically);
				values = filter.Apply(values);
			}

			return _ValuesToText.Apply(values);
		}
        } // ImageGridViewColumn

        // ----------------------------------------------------------------------
        protected ImageGridViewColumn(Stretch imageStretch)
        {
            FrameworkElementFactory imageElement = new FrameworkElementFactory(typeof(Image));

            // image source
            Binding imageSourceBinding = new Binding();
            imageSourceBinding.Converter = this;
            imageSourceBinding.Mode = BindingMode.OneWay;
            imageElement.SetBinding(Image.SourceProperty, imageSourceBinding);

            // image stretching
            Binding imageStretchBinding = new Binding();
            imageStretchBinding.Source = imageStretch;
            imageElement.SetBinding(Image.StretchProperty, imageStretchBinding);

            DataTemplate template = new DataTemplate();
            template.VisualTree = imageElement;
            CellTemplate = template;
        } // ImageGridViewColumn
Exemple #10
0
		public static void ApplyTemplate(FrameworkElement item, ImageBrush brush, ContentControl contentBody, Stretch stretch, DependencyProperty imageDependencyProperty)
		{
			SetStretch(brush, stretch);

			if (contentBody != null)
			{
				var bottom = -(contentBody.FontSize / 8.0);
				var top = -(contentBody.FontSize / 2.0) - bottom;

				contentBody.Margin = new Thickness(0, top, 0, bottom);
			}
			
			var image = item.GetValue(imageDependencyProperty) as ImageSource;

			if (image == null)
				item.SetValue(imageDependencyProperty, new BitmapImage(new Uri("/Coding4Fun.Phone.Controls;component/Media/icons/appbar.check.rest.png", UriKind.RelativeOrAbsolute)));
			else 
				SetImageBrush(brush, image);
		}
Exemple #11
0
        public PhotoViewModel()
        {
            _currentPhoto = null;
              _imageDirectory = null;
              _imageNumber = 0;
              _imageCount = 0;
              _imageFiles = new List<string>();
              _photos = new PhotoCollection();
              _photoDisplayMode = Stretch.Uniform;

              registerCommands();

              //Task.Run(() =>
              //  {
              if (Environment.GetCommandLineArgs().Length > 1)
            loadImages(Environment.GetCommandLineArgs()[1]);
              else
            //LoadImages("C:\\Users\\Ryan\\Pictures\\sky, space and landscapes\\3r4en.jpg");
            loadImages("C:\\Users\\Public\\Pictures\\Sample Pictures\\Desert.jpg");
              //});
        }
Exemple #12
0
        /// <summary>
        /// Conerts a drawing into a bitmap object compatible with System.Drawing.
        /// </summary>
        /// <param name="drawing"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="stretch"></param>
        /// <returns></returns>
        public static System.Drawing.Bitmap DrawingToBitmap(Drawing drawing, int width, int height, Stretch stretch = Stretch.None)
        {
            var encoder = new PngBitmapEncoder();
            var drawingImage = new DrawingImage(drawing);

            var image = new Image() { Source = drawingImage };
            image.Stretch = stretch;
            image.HorizontalAlignment = HorizontalAlignment.Left;
            image.VerticalAlignment = VerticalAlignment.Top;
            image.Arrange(new Rect(0, 0, width, height));

            var bitmap = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32);
            bitmap.Render(image);

            encoder.Frames.Add(BitmapFrame.Create(bitmap));

            var stream = new MemoryStream();
            encoder.Save(stream);

            return new System.Drawing.Bitmap(stream);
        }
 public void IsZero()
 {
     Assert.IsTrue(Stretch.Between(TestData.Hövik, TestData.Hövik).IsZero);
 }
Exemple #14
0
        private void Update(EvaluationContext context)
        {
            try
            {
                var resourceManager = ResourceManager.Instance();

                var scale    = Scale.GetValue(context);
                var stretch  = Stretch.GetValue(context);
                var pivot    = Pivot.GetValue(context);
                var rotation = Rotation.GetValue(context);

                float yaw   = MathUtil.DegreesToRadians(rotation.Y);
                float pitch = MathUtil.DegreesToRadians(rotation.X);
                float roll  = MathUtil.DegreesToRadians(rotation.Z);

                var rotationMatrix = Matrix.RotationYawPitchRoll(yaw, pitch, roll);

                //var offset =

                var center = Center.GetValue(context);
                //var centerRotated = SharpDX.Vector3.Transform(new SharpDX.Vector3(center.X, center.Y, center.Z), rotationMatrix);
                var offset = new SharpDX.Vector3(stretch.X * scale * (pivot.X - 0.5f),
                                                 stretch.Y * scale * (pivot.Y - 0.5f),
                                                 0);

                var center2 = new SharpDX.Vector3(center.X, center.Y, center.Z);

                var segments = Segments.GetValue(context);
                var rows     = segments.Width.Clamp(1, 10000) + 1;
                var columns  = segments.Height.Clamp(1, 10000) + 1;

                var faceCount     = (columns - 1) * (rows - 1) * 2;
                var verticesCount = columns * rows;

                // Create buffers
                if (_vertexBufferData.Length != verticesCount)
                {
                    _vertexBufferData = new PbrVertex[verticesCount];
                }

                if (_indexBufferData.Length != faceCount)
                {
                    _indexBufferData = new SharpDX.Int3[faceCount];
                }

                double columnStep = (scale * stretch.X) / (columns - 1);
                double rowStep    = (scale * stretch.Y) / (rows - 1);

                // var normal = SharpDX.Vector3.ForwardRH;
                // var tangent = SharpDX.Vector3.Right;
                // var binormal = SharpDX.Vector3.Up;

                var normal   = SharpDX.Vector3.TransformNormal(SharpDX.Vector3.ForwardLH, rotationMatrix);
                var tangent  = SharpDX.Vector3.TransformNormal(SharpDX.Vector3.Right, rotationMatrix);
                var binormal = SharpDX.Vector3.TransformNormal(SharpDX.Vector3.Up, rotationMatrix);

                // Initialize
                for (int columnIndex = 0; columnIndex < columns; ++columnIndex)
                {
                    var columnFragment = (float)(columnIndex * columnStep);

                    var u0 = columnIndex / ((float)columns - 1);
                    //var v1 = (columnIndex + 1) / (float)columns;

                    for (int rowIndex = 0; rowIndex < rows; ++rowIndex)
                    {
                        var rowFragment = (float)(rowIndex * rowStep);
                        //var rowFragment = ((float)rowIndex / rows - pivot.Y) * stretch.Y;

                        var vertexIndex = rowIndex + columnIndex * rows;
                        var faceIndex   = 2 * (rowIndex + columnIndex * (rows - 1));


                        var p = new SharpDX.Vector3(columnFragment,
                                                    rowFragment,
                                                    0);

                        var v0  = (rowIndex) / ((float)rows - 1);
                        var uv0 = new SharpDX.Vector2(u0, v0);
                        _vertexBufferData[vertexIndex + 0] = new PbrVertex
                        {
                            Position  = SharpDX.Vector3.TransformNormal(p + offset, rotationMatrix) + center2,
                            Normal    = normal,
                            Tangent   = tangent,
                            Bitangent = binormal,
                            Texcoord  = uv0,
                            Selection = 1,
                        };

                        if (columnIndex >= columns - 1 || rowIndex >= rows - 1)
                        {
                            continue;
                        }

                        _indexBufferData[faceIndex + 0] = new SharpDX.Int3(vertexIndex, vertexIndex + rows, vertexIndex + 1);
                        _indexBufferData[faceIndex + 1] = new SharpDX.Int3(vertexIndex + rows, vertexIndex + rows + 1, vertexIndex + 1);
                    }
                }

                // Write Data
                _vertexBufferWithViews.Buffer = _vertexBuffer;
                resourceManager.SetupStructuredBuffer(_vertexBufferData, PbrVertex.Stride * verticesCount, PbrVertex.Stride, ref _vertexBuffer);
                resourceManager.CreateStructuredBufferSrv(_vertexBuffer, ref _vertexBufferWithViews.Srv);
                resourceManager.CreateStructuredBufferUav(_vertexBuffer, UnorderedAccessViewBufferFlags.None, ref _vertexBufferWithViews.Uav);

                _indexBufferWithViews.Buffer = _indexBuffer;
                const int stride = 3 * 4;
                resourceManager.SetupStructuredBuffer(_indexBufferData, stride * faceCount, stride, ref _indexBuffer);
                resourceManager.CreateStructuredBufferSrv(_indexBuffer, ref _indexBufferWithViews.Srv);
                resourceManager.CreateStructuredBufferUav(_indexBuffer, UnorderedAccessViewBufferFlags.None, ref _indexBufferWithViews.Uav);

                _data.VertexBuffer  = _vertexBufferWithViews;
                _data.IndicesBuffer = _indexBufferWithViews;
                Data.Value          = _data;
                Data.DirtyFlag.Clear();
            }
            catch (Exception e)
            {
                Log.Error("Failed to create torus mesh:" + e.Message);
            }
        }
 public void EqualsIsCorrect()
 {
     Assert.AreEqual(Stretch.Between(TestData.Stockholm, TestData.Wellington), Stretch.Between(TestData.Stockholm, TestData.Wellington));
     Assert.AreNotEqual(Stretch.Between(TestData.Stockholm, TestData.Wellington), Stretch.Between(TestData.Hövik, TestData.Höviksnäs));
     Assert.AreNotEqual(Stretch.Between(TestData.Stockholm, TestData.Wellington), new object());
 }
        public void IsEastWestLine()
        {
            var target = Stretch.Between(Position.FromDegrees(50, -4), Position.FromDegrees(50, 87));

            Assert.IsTrue(target.IsEastWestLine);
        }
Exemple #17
0
        static Size ComputeScaleFactor(Size availableSize, Size contentSize, Stretch stretch, StretchDirection stretchDirection)
        {
            double widthFactor  = 1.0;
            double heightFactor = 1.0;
            bool   widthSet     = !double.IsPositiveInfinity(availableSize.Width);
            bool   heightSet    = !double.IsPositiveInfinity(availableSize.Height);

            if ((stretch == Stretch.Uniform || stretch == Stretch.UniformToFill || stretch == Stretch.Fill) && (widthSet || heightSet))
            {
                widthFactor  = (IsZero(contentSize.Width) ? 0.0 : (availableSize.Width / contentSize.Width));
                heightFactor = (IsZero(contentSize.Height) ? 0.0 : (availableSize.Height / contentSize.Height));
                if (!widthSet)
                {
                    widthFactor = heightFactor;
                }
                else
                {
                    if (!heightSet)
                    {
                        heightFactor = widthFactor;
                    }
                    else
                    {
                        switch (stretch)
                        {
                        case Stretch.Uniform:
                        {
                            double num3 = (widthFactor < heightFactor) ? widthFactor : heightFactor;
                            heightFactor = (widthFactor = num3);
                            break;
                        }

                        case Stretch.UniformToFill:
                        {
                            double num4 = (widthFactor > heightFactor) ? widthFactor : heightFactor;
                            heightFactor = (widthFactor = num4);
                            break;
                        }
                        }
                    }
                }
                switch (stretchDirection)
                {
                case StretchDirection.UpOnly:
                    if (widthFactor < 1.0)
                    {
                        widthFactor = 1.0;
                    }
                    if (heightFactor < 1.0)
                    {
                        heightFactor = 1.0;
                    }
                    break;

                case StretchDirection.DownOnly:
                    if (widthFactor > 1.0)
                    {
                        widthFactor = 1.0;
                    }
                    if (heightFactor > 1.0)
                    {
                        heightFactor = 1.0;
                    }
                    break;
                }
            }
            return(new Size(widthFactor, heightFactor));
        }
Exemple #18
0
        /// <summary>
        /// Updates the CompositionSurfaceBrush's Stretch and Alignment options
        /// </summary>
        /// <param name="surfaceBrush">CompositionSurfaceBrush</param>
        /// <param name="stretch">Stretch mode</param>
        /// <param name="alignX">Horizontal Alignment</param>
        /// <param name="alignY">Vertical Alignment</param>
        /// <param name="alignXAnimation">The animation to use to update the horizontal alignment of the surface brush</param>
        /// <param name="alignYAnimation">The animation to use to update the vertical alignment of the surface brush</param>
        public static void UpdateSurfaceBrushOptions(this CompositionSurfaceBrush surfaceBrush, Stretch stretch,
                                                     AlignmentX alignX, AlignmentY alignY, ScalarKeyFrameAnimation alignXAnimation = null,
                                                     ScalarKeyFrameAnimation alignYAnimation = null)
        {
            // Stretch Mode
            switch (stretch)
            {
            case Stretch.None:
                surfaceBrush.Stretch = CompositionStretch.None;
                break;

            case Stretch.Fill:
                surfaceBrush.Stretch = CompositionStretch.Fill;
                break;

            case Stretch.Uniform:
                surfaceBrush.Stretch = CompositionStretch.Uniform;
                break;

            case Stretch.UniformToFill:
                surfaceBrush.Stretch = CompositionStretch.UniformToFill;
                break;
            }

            // Horizontal Alignment
            var finalAlignX = surfaceBrush.HorizontalAlignmentRatio;

            switch (alignX)
            {
            case AlignmentX.Left:
                finalAlignX = 0;
                break;

            case AlignmentX.Center:
                finalAlignX = 0.5f;
                break;

            case AlignmentX.Right:
                finalAlignX = 1;
                break;
            }

            // If animation is available, animate to the new value
            // otherwise set it explicitly
            if (alignXAnimation == null)
            {
                surfaceBrush.HorizontalAlignmentRatio = finalAlignX;
            }
            else
            {
                alignXAnimation.InsertKeyFrame(1f, finalAlignX);
                surfaceBrush.StartAnimation("HorizontalAlignmentRatio", alignXAnimation);
            }

            // Vertical Alignment
            var finalAlignY = surfaceBrush.VerticalAlignmentRatio;

            switch (alignY)
            {
            case AlignmentY.Top:
                finalAlignY = 0;
                break;

            case AlignmentY.Center:
                finalAlignY = 0.5f;
                break;

            case AlignmentY.Bottom:
                finalAlignY = 1;
                break;
            }

            // If animation is available, animate to the new value
            // otherwise set it explicitly
            if (alignYAnimation == null)
            {
                surfaceBrush.VerticalAlignmentRatio = finalAlignY;
            }
            else
            {
                alignYAnimation.InsertKeyFrame(1f, finalAlignY);
                surfaceBrush.StartAnimation("VerticalAlignmentRatio", alignYAnimation);
            }
        }
Exemple #19
0
 public void DeleteStretch(Stretch st)
 {
     stretches.Remove(st);
 }
Exemple #20
0
    public IEnumerator ParametersFromFRCMODFile(string filename, Parameters parameters)
    {
        string[] lines    = FileIO.Readlines(filename);
        int      maxLines = lines.Length;

        List <string> sections = new List <string> {
            "MASS",
            "BOND",
            "ANGL",
            "DIHE",
            "IMPR",
            "NONB",
            "IPOL",
            "CMAP",
            "%"
        };
        string sectionName;
        int    sectionNum  = 0;
        int    numSections = sections.Count;

        string section = "";

        string restOfLine;

        string[] splitLine;

        Stretch         newStretchParam;
        Bend            newBendParam;
        Torsion         newTorsionParam;
        ImproperTorsion newImproperTorsionParam;
        VdW             newVdWParam;

        Torsion existingTorsionParam;
        int     existingTorsionNum;
        bool    torsionModified;

        int offset;

        foreach (string line in lines)
        {
            if (line == "")
            {
                continue;
            }

            for (sectionNum = 0; sectionNum < numSections; sectionNum++)
            {
                sectionName = sections [sectionNum];
                if (line.StartsWith(sectionName))
                {
                    section = sectionName;
                    goto SKIP;
                }
            }

            //Ignore MASS section

            //Parse Bond
            if (section == "BOND")
            {
                t0 = GetAmberFromString(line, 0);
                t1 = GetAmberFromString(line, 3);

                restOfLine = line.Substring(5, line.Length - 6);
                splitLine  = restOfLine.Split(new [] { " " }, System.StringSplitOptions.RemoveEmptyEntries);

                keq = float.Parse(splitLine [0]);
                req = float.Parse(splitLine [1]);

                newStretchParam = new Stretch(t0, t1, req, keq);
                parameters.AddStretch(newStretchParam);
            }
            else if (section == "ANGL")
            {
                t0 = GetAmberFromString(line, 0);
                t1 = GetAmberFromString(line, 3);
                t2 = GetAmberFromString(line, 6);

                restOfLine = line.Substring(8, line.Length - 9);
                splitLine  = restOfLine.Split(new [] { " " }, System.StringSplitOptions.RemoveEmptyEntries);

                keq = float.Parse(splitLine [0]);
                req = float.Parse(splitLine [1]);

                newBendParam = new Bend(t0, t1, t2, req, keq);
                parameters.AddBend(newBendParam);
            }
            else if (section == "DIHE")
            {
                t0 = GetAmberFromString(line, 0);
                t1 = GetAmberFromString(line, 3);
                t2 = GetAmberFromString(line, 6);
                t3 = GetAmberFromString(line, 9);

                newTorsionParam = new Torsion(t0, t1, t2, t3);

                restOfLine = line.Substring(11, line.Length - 12);
                splitLine  = restOfLine.Split(new [] { " " }, System.StringSplitOptions.RemoveEmptyEntries);

                npaths      = int.Parse(splitLine [0]);
                v           = float.Parse(splitLine [1]);
                gamma       = float.Parse(splitLine [2]);
                periodicity = (int)Mathf.Abs(float.Parse(splitLine [3]));

                //The same param can be defined on multiple lines
                torsionModified = false;

                for (existingTorsionNum = 0; existingTorsionNum < parameters.torsions.Count; existingTorsionNum++)
                {
                    existingTorsionParam = parameters.torsions [existingTorsionNum];
                    if (existingTorsionParam.TypeEquivalent(newTorsionParam))
                    {
                        existingTorsionParam.Modify(periodicity, v, gamma);
                        torsionModified = true;
                    }
                }


                if (!torsionModified)
                {
                    newTorsionParam.npaths = npaths;
                    if (periodicity == 1)
                    {
                        newTorsionParam.v0     = v;
                        newTorsionParam.gamma0 = gamma;
                    }
                    else if (periodicity == 2)
                    {
                        newTorsionParam.v1     = v;
                        newTorsionParam.gamma1 = gamma;
                    }
                    else if (periodicity == 3)
                    {
                        newTorsionParam.v2     = v;
                        newTorsionParam.gamma2 = gamma;
                    }
                    else if (periodicity == 4)
                    {
                        newTorsionParam.v3     = v;
                        newTorsionParam.gamma3 = gamma;
                    }

                    yield return(null);

                    parameters.AddTorsion(newTorsionParam);
                }
            }
            else if (section == "IMPR")
            {
                t0 = GetAmberFromString(line, 0);
                t1 = GetAmberFromString(line, 3);
                t2 = GetAmberFromString(line, 6);
                t3 = GetAmberFromString(line, 9);

                restOfLine = line.Substring(11, line.Length - 12);
                splitLine  = restOfLine.Split(new [] { " " }, System.StringSplitOptions.RemoveEmptyEntries);

                offset = 1;

                //Sometimes npaths is included here, even though ignored. Sometimes it's not.
                if (splitLine [0].Contains("."))
                {
                    offset = 0;
                }

                v           = float.Parse(splitLine [offset]);
                gamma       = float.Parse(splitLine [offset + 1]);
                periodicity = (int)Mathf.Abs(float.Parse(splitLine [offset + 2]));

                newImproperTorsionParam = new ImproperTorsion(t0, t1, t2, t3, v, gamma, periodicity);

                parameters.AddImproperTorsion(newImproperTorsionParam);
            }
            else if (section == "NONB")
            {
                splitLine = line.Split(new [] { " " }, System.StringSplitOptions.RemoveEmptyEntries);

                t      = splitLine [0];
                radius = float.Parse(splitLine [1]);
                v      = float.Parse(splitLine [2]);

                newVdWParam = new VdW(t, radius, v);

                parameters.AddVdW(newVdWParam);
            }

            SKIP :;
        }
    }
        public void TestLayoutAsync()
        {
            // prepare paramters for TestBase.TestTaskAsync
            Viewbox vb = new Viewbox()
            {
                Width  = 400,
                Height = 400
            };
            ScrollViewer sv = new ScrollViewer()
            {
                Background = new SolidColorBrush(Colors.Blue)
            };
            Rectangle r = new Rectangle()
            {
                StrokeThickness = 1,
                Stroke          = new SolidColorBrush(Colors.Red),
                Fill            = new SolidColorBrush(Colors.Green)
            };
            List <Action> actions = new List <Action>();

            // this is ugly, because there is no Enum.GetValues() in Silverlight
            Stretch[]          stretches         = { Stretch.None, Stretch.Fill, Stretch.Uniform, Stretch.UniformToFill };
            StretchDirection[] stretchDirections = { StretchDirection.UpOnly, StretchDirection.DownOnly, StretchDirection.Both };

            // generate all possible test cases
            // Viewbox properties: Stretch & StretchDirection
            foreach (Stretch s in stretches)
            {
                foreach (StretchDirection sd in stretchDirections)
                {
                    // Rectangle properties: Width, Height
                    for (double width = 4; width <= 800; width *= 200)
                    {
                        for (double height = 4; height <= 800; height *= 200)
                        {
                            // capture loop variables
                            Stretch          cs  = s;
                            StretchDirection csd = sd;
                            double           cw  = width;
                            double           ch  = height;

                            // First, add Rectangle into Viewbox directly
                            actions.Add(() =>
                            {
                                vb.Stretch          = cs;
                                vb.StretchDirection = csd;
                                r.Width             = cw;
                                r.Height            = ch;

                                sv.Content = null;     // free r for next line
                                vb.Child   = r;
                            });

                            actions.Add(() =>
                            {
                                Rect original = new Rect(0, 0, cw, ch);
                                Rect expected = CalculateExpectedLayout(vb, r);
                                Rect actual   = CalculateActualLayout(vb, r);

                                Size sizeExpected = new Size(expected.Width, expected.Height);
                                Size sizeActual   = new Size(actual.Width, actual.Height);

                                Assert.AreEqual(
                                    sizeExpected,
                                    sizeActual,
                                    "Viewbox({0},{1})|Rect({2},{3}): orignal [{4}], expected [{5}] actual [{6}].",
                                    vb.Stretch,
                                    vb.StretchDirection,
                                    r.HorizontalAlignment,
                                    r.VerticalAlignment,
                                    original,
                                    expected,
                                    actual);
                            });

                            // Then, add Rectangle into Viewbox via a ScrollViewer
                            actions.Add(() =>
                            {
                                vb.Child   = sv;
                                sv.Content = r;
                            });

                            actions.Add(() =>
                            {
                                Rect original = new Rect(0, 0, cw, ch);
                                Rect expected = original;     // ScrollViewer prevent Viewbox stretching
                                Rect actual   = new Rect(0, 0, r.ActualWidth, r.ActualHeight);

                                Size sizeExpected = new Size(expected.Width, expected.Height);
                                Size sizeActual   = new Size(actual.Width, actual.Height);

                                Assert.AreEqual(
                                    sizeExpected,
                                    sizeActual,
                                    "Viewbox({0},{1})|ScrollViewer|Rect({2},{3}): orignal [{4}], expected [{5}] actual [{6}].",
                                    vb.Stretch,
                                    vb.StretchDirection,
                                    r.HorizontalAlignment,
                                    r.VerticalAlignment,
                                    original,
                                    expected,
                                    actual);
                            });
                        }
                    }
                }
            }

            TestAsync(5, vb, actions.ToArray());
        }
        public static GeometryModel3DElement ConvertImageTo3D(SceneViewModel viewModel, BaseFrameworkElement imageElement, string newName, out ImageBrushNode imageBrush)
        {
            imageBrush = (ImageBrushNode)viewModel.CreateSceneNode(typeof(ImageBrush));
            string    uri = ((ImageElement)imageElement).Uri;
            SceneNode valueAsSceneNode = imageElement.GetLocalValueAsSceneNode(ImageElement.SourceProperty);

            if (valueAsSceneNode != null)
            {
                imageBrush.ImageSource = viewModel.GetSceneNode(valueAsSceneNode.DocumentNode.Clone(viewModel.Document.DocumentContext));
            }
            double      num         = 1.0;
            double      imageWidth  = 1.0;
            double      imageHeight = 1.0;
            double      width       = 1.0;
            double      height      = 1.0;
            Stretch     stretch     = Stretch.Fill;
            ImageSource imageSource;

            if (imageElement.Visual != null)
            {
                Rect computedTightBounds = imageElement.GetComputedTightBounds();
                num         = computedTightBounds.Width / computedTightBounds.Height;
                imageWidth  = computedTightBounds.Width;
                imageHeight = computedTightBounds.Height;
                imageSource = imageElement.GetComputedValue(ImageElement.SourceProperty) as ImageSource;
                stretch     = (Stretch)imageElement.GetComputedValue(ImageElement.StretchProperty);
            }
            else
            {
                imageSource = imageElement.GetLocalOrDefaultValue(ImageElement.SourceProperty) as ImageSource;
                object localOrDefaultValue = imageElement.GetLocalOrDefaultValue(ImageElement.StretchProperty);
                if (localOrDefaultValue is Stretch)
                {
                    stretch = (Stretch)localOrDefaultValue;
                }
            }
            if (imageSource != null)
            {
                width  = imageSource.Width;
                height = imageSource.Height;
            }
            imageBrush.SetValue(TileBrushNode.StretchProperty, (object)stretch);
            if (stretch == Stretch.None)
            {
                double x = 0.0;
                double y = 0.0;
                if (imageWidth > width)
                {
                    x = (imageWidth - width) / 2.0;
                }
                if (imageHeight > height)
                {
                    y = (imageHeight - height) / 2.0;
                }
                imageBrush.SetValue(TileBrushNode.ViewportUnitsProperty, (object)BrushMappingMode.Absolute);
                imageBrush.SetValue(TileBrushNode.ViewportProperty, (object)new Rect(x, y, width, height));
            }
            GeometryModel3D geometryModel3D = new GeometryModel3D();

            geometryModel3D.Geometry = (Geometry3D)GeometryCreationHelper3D.CreateSubdividedQuad(9, 20.0 * num, 20.0, imageWidth, imageHeight);
            GeometryModel3DElement geometryModel3Delement = (GeometryModel3DElement)viewModel.CreateSceneNode((object)geometryModel3D);

            geometryModel3Delement.Name             = SceneNodeIDHelper.ToCSharpID(newName);
            geometryModel3Delement.DesignTimeBounds = geometryModel3D.Bounds;
            DiffuseMaterialNode diffuseMaterialNode = (DiffuseMaterialNode)viewModel.CreateSceneNode(typeof(DiffuseMaterial));

            diffuseMaterialNode.Brush       = (SceneNode)imageBrush;
            geometryModel3Delement.Material = (MaterialNode)diffuseMaterialNode;
            BitmapImageNode bitmapImageNode = imageBrush.ImageSource as BitmapImageNode;

            if (bitmapImageNode != null && uri != null)
            {
                bitmapImageNode.SetValue(BitmapImageNode.UriSourceProperty, (object)new Uri(uri, UriKind.RelativeOrAbsolute));
            }
            return(geometryModel3Delement);
        }
Exemple #23
0
 /// <summary>
 /// Calculates a scaled size based on a <see cref="Stretch"/> value.
 /// </summary>
 /// <param name="stretch">The stretch mode.</param>
 /// <param name="destinationSize">The size of the destination viewport.</param>
 /// <param name="sourceSize">The size of the source.</param>
 /// <returns>The size of the stretched source.</returns>
 public static Size CalculateSize(this Stretch stretch, Size destinationSize, Size sourceSize)
 {
     return(sourceSize * stretch.CalculateScaling(destinationSize, sourceSize));
 }
Exemple #24
0
        public static void ApplyTemplate(FrameworkElement item, ImageBrush brush, ContentControl contentBody, Stretch stretch, DependencyProperty imageDependencyProperty)
        {
            SetStretch(brush, stretch);

            if (contentBody != null)
            {
                var bottom = -(contentBody.FontSize / 8.0);
                var top    = -(contentBody.FontSize / 2.0) - bottom;

                contentBody.Margin = new Thickness(0, top, 0, bottom);
            }

            var image = item.GetValue(imageDependencyProperty) as ImageSource;

            if (image == null)
            {
                item.SetValue(imageDependencyProperty, new BitmapImage(new Uri("/Coding4Fun.Phone.Controls;component/Media/icons/appbar.check.rest.png", UriKind.RelativeOrAbsolute)));
            }
            else
            {
                SetImageBrush(brush, image);
            }
        }
Exemple #25
0
    public Vector3 GetClosestTangent(Vector3 worldPos)
    {
        Stretch st = GetClosestStretch(worldPos);

        return(st.GetTangentAtClosestPoint(worldPos));
    }
        private static void AddImage(Func <FileStream> fileStreamFunc, WorksheetPart worksheetPart)
        {
            if (fileStreamFunc == null)
            {
                return;
            }

            DrawingsPart drawingsPart;
            ImagePart    imagePart;
            Extents      extents;

            using (var fileStream = fileStreamFunc())
            {
                if (fileStream == null)
                {
                    return;
                }

                drawingsPart = worksheetPart.AddNewPart <DrawingsPart>();
                imagePart    = drawingsPart.AddImagePart(ImagePartType.Png, worksheetPart.GetIdOfPart(drawingsPart));
                imagePart.FeedData(fileStream);

                Image image = Image.FromStream(fileStream);
                //http://en.wikipedia.org/wiki/English_Metric_Unit#DrawingML
                //http://stackoverflow.com/questions/1341930/pixel-to-centimeter
                //http://stackoverflow.com/questions/139655/how-to-convert-pixels-to-points-px-to-pt-in-net-c
                extents = new Extents
                {
                    Cx = (long)image.Width * (long)((float)914400 / image.HorizontalResolution),
                    Cy = (long)image.Height * (long)((float)914400 / image.VerticalResolution)
                };
                image.Dispose();
            }

            NonVisualPictureProperties pictureNonVisualPictureProperties =
                new NonVisualPictureProperties
            {
                NonVisualDrawingProperties = new NonVisualDrawingProperties
                {
                    Id          = 1025,
                    Name        = "Picture 1",
                    Description = "eventtree"
                },
                NonVisualPictureDrawingProperties = new NonVisualPictureDrawingProperties
                {
                    PictureLocks = new PictureLocks
                    {
                        NoChangeAspect     = true,
                        NoChangeArrowheads = true
                    }
                }
            };

            Stretch stretch =
                new Stretch
            {
                FillRectangle = new FillRectangle()
            };

            BlipFill blipFill = new BlipFill
            {
                Blip = new Blip
                {
                    Embed            = drawingsPart.GetIdOfPart(imagePart),
                    CompressionState = BlipCompressionValues.Print
                },
                SourceRectangle = new SourceRectangle()
            };

            blipFill.Append(stretch);

            ShapeProperties shapeProperties =
                new ShapeProperties
            {
                BlackWhiteMode = BlackWhiteModeValues.Auto,
                Transform2D    = new Transform2D
                {
                    Offset = new Offset
                    {
                        X = 0,
                        Y = 0
                    },
                    Extents = extents
                }
            };
            PresetGeometry prstGeom =
                new PresetGeometry
            {
                Preset          = ShapeTypeValues.Rectangle,
                AdjustValueList = new AdjustValueList()
            };

            shapeProperties.Append(prstGeom);
            shapeProperties.Append(new SolidFill
            {
                RgbColorModelHex = new RgbColorModelHex
                {
                    Val = Color.White.ToSimpleHexValue()
                }
            });
            DocumentFormat.OpenXml.Drawing.Outline outline = new DocumentFormat.OpenXml.Drawing.Outline
            {
                Width = 25400,
            };

            var solidFill1 = new SolidFill
            {
                RgbColorModelHex = new RgbColorModelHex
                {
                    Val = StyleSheetLibrary.BorderColor.ToSimpleHexValue()
                }
            };

            outline.Append(solidFill1);
            shapeProperties.Append(outline);

            DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture picture =
                new DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture
            {
                NonVisualPictureProperties = pictureNonVisualPictureProperties,
                BlipFill        = blipFill,
                ShapeProperties = shapeProperties
            };

            var           iColumnId     = 11;
            var           iRowId        = 1;
            var           lColumnOffset = 0;
            var           lRowOffset    = 0;
            OneCellAnchor ocanchor      = new OneCellAnchor
            {
                FromMarker = new DocumentFormat.OpenXml.Drawing.Spreadsheet.FromMarker
                {
                    ColumnId = new ColumnId {
                        Text = iColumnId.ToString(CultureInfo.InvariantCulture)
                    },
                    ColumnOffset = new ColumnOffset {
                        Text = lColumnOffset.ToString(CultureInfo.InvariantCulture)
                    },
                    RowId = new RowId {
                        Text = iRowId.ToString(CultureInfo.InvariantCulture)
                    },
                    RowOffset = new RowOffset {
                        Text = lRowOffset.ToString(CultureInfo.InvariantCulture)
                    }
                },
                Extent = new Extent {
                    Cx = extents.Cx, Cy = extents.Cy
                }
            };

            ocanchor.Append(picture);
            ocanchor.Append(new ClientData());


            WorksheetDrawing worksheetDrawing = new WorksheetDrawing();

            worksheetDrawing.Append(ocanchor);
            Drawing drawing = new Drawing {
                Id = drawingsPart.GetIdOfPart(imagePart)
            };

            worksheetDrawing.Save(drawingsPart);

            worksheetPart.Worksheet.Append(drawing);
        }
    public override void Render(RenderContext renderContext, Stretch stretchMode, StretchDirection stretchDirection)
    {
      Allocate();

      Texture currentTexture = CurrentTexture;
      SizeF currentRawSourceSize = CurrentRawSourceSize;
      RectangleF currentTextureClip = CurrentTextureClip;
      Vector4 frameData = new Vector4(currentRawSourceSize.Width, currentRawSourceSize.Height, (float) EffectTimer, 0);

      if (_transitionActive)
      {
        double elapsed = (SkinContext.FrameRenderingStartTime - _transitionStart).TotalSeconds / Math.Max(TransitionDuration, 0.01);
        if (elapsed > 1.0)
          _transitionActive = false;
        else
        {
          Texture lastTexture = LastTexture;
          SizeF lastRawSourceSize = LastRawSourceSize;
          RectangleF lastTextureClip = LastTextureClip;
          Vector4 lastFrameData = new Vector4(lastRawSourceSize.Width, lastRawSourceSize.Height, (float) EffectTimer, 0);

          Texture start = lastTexture ?? NullTexture.Texture;
          Texture end = currentTexture ?? NullTexture.Texture;

          if (start != end)
          {
            SizeF startSize = StretchSource(_lastImageContext.RotatedFrameSize, lastRawSourceSize, stretchMode, stretchDirection);
            SizeF endSize = StretchSource(_imageContext.RotatedFrameSize, currentRawSourceSize, stretchMode, stretchDirection);

            // Render transition from last texture to current texture
            _lastImageContext.Update(startSize, start, lastTextureClip);

            if (_imageContext.StartRenderTransition(renderContext, (float) elapsed, _lastImageContext,
                endSize, end, currentTextureClip, BorderColor, lastFrameData, frameData))
            {
              _primitiveBuffer.Render(0);
              _imageContext.EndRenderTransition();
            }
          }
          return;
        }
      }

      if (IsAllocated)
      {
        SizeF sourceSize = StretchSource(_imageContext.RotatedFrameSize, currentRawSourceSize, stretchMode, stretchDirection);
        if (_imageContext.StartRender(renderContext, sourceSize, currentTexture, currentTextureClip, BorderColor, frameData))
        {
          _primitiveBuffer.Render(0);
          _imageContext.EndRender();
        }
      }
    }
Exemple #28
0
 private void StretchPropertyChanged(Stretch stretch)
 {
     internalImage.Stretch = stretch;
 }
 public static void SetImageStretch(DependencyObject obj, Stretch value)
 {
     obj.SetValue(ImageStretchProperty, value);
 }
Exemple #30
0
    //This can be used to read parameters from gaussian input files as well
    public Parameters ParametersFromPRMLines(string[] lines)
    {
        Parameters parameters = Instantiate <Parameters>(parametersPrefab);

        int    vType;
        int    cType;
        int    vCutoff;
        int    cCutoff;
        float  vScale1;
        float  vScale2;
        float  vScale3;
        float  cScale1;
        float  cScale2;
        float  cScale3;
        string t0;
        string t1;
        string t2;
        string t3;
        float  req;
        float  keq;
        float  v;
        float  v0;
        float  v1;
        float  v2;
        float  v3;
        float  gamma;
        float  gamma0;
        float  gamma1;
        float  gamma2;
        float  gamma3;
        int    npaths;
        int    periodicity;

        foreach (string line in lines)
        {
            string[] splitLine = line.Split(new [] { " " }, System.StringSplitOptions.RemoveEmptyEntries);
            if (splitLine.Length == 0)
            {
                continue;
            }
            if (splitLine [0].ToUpper() == "NONBON")
            {
                vType   = int.Parse(splitLine [1]);
                cType   = int.Parse(splitLine [2]);
                vCutoff = int.Parse(splitLine [3]);
                cCutoff = int.Parse(splitLine [4]);
                vScale1 = float.Parse(splitLine [5]);
                vScale2 = float.Parse(splitLine [6]);
                vScale3 = float.Parse(splitLine [7]);
                cScale1 = float.Parse(splitLine [8]);
                cScale2 = float.Parse(splitLine [9]);
                cScale3 = float.Parse(splitLine [10]);

                parameters.nonbonding = new NonBonding(vType, cType, vCutoff, cCutoff, vScale1, vScale2, vScale3, cScale1, cScale2, cScale3);
            }
            else if (splitLine [0].ToUpper().StartsWith("HRMSTR"))
            {
                t0  = splitLine [1];
                t1  = splitLine [2];
                req = float.Parse(splitLine [3]);
                keq = float.Parse(splitLine [4]);

                Stretch stretch = new Stretch(t0, t1, req, keq);
                parameters.stretches.Add(stretch);
            }
            else if (splitLine [0].ToUpper().StartsWith("HRMBND"))
            {
                t0  = splitLine [1];
                t1  = splitLine [2];
                t2  = splitLine [3];
                req = float.Parse(splitLine [4]);
                keq = float.Parse(splitLine [5]);

                Bend bend = new Bend(t0, t1, t2, req, keq);
                parameters.bends.Add(bend);
            }
            else if (splitLine [0].ToUpper().StartsWith("AMBTRS"))
            {
                t0     = splitLine [1];
                t1     = splitLine [2];
                t2     = splitLine [3];
                t3     = splitLine [4];
                v0     = float.Parse(splitLine [5]);
                v1     = float.Parse(splitLine [6]);
                v2     = float.Parse(splitLine [7]);
                v3     = float.Parse(splitLine [8]);
                gamma0 = float.Parse(splitLine [9]);
                gamma1 = float.Parse(splitLine [10]);
                gamma2 = float.Parse(splitLine [11]);
                gamma3 = float.Parse(splitLine [12]);
                npaths = (int)float.Parse(splitLine [13]);

                Torsion torsion = new Torsion(t0, t1, t2, t3, v0, v1, v2, v3, gamma0, gamma1, gamma2, gamma3, npaths);
                parameters.torsions.Add(torsion);
            }
            else if (splitLine [0].ToUpper().StartsWith("IMPTRS"))
            {
                t0          = splitLine [1];
                t1          = splitLine [2];
                t2          = splitLine [3];
                t3          = splitLine [4];
                v           = float.Parse(splitLine [5]);;
                gamma       = float.Parse(splitLine [6]);
                periodicity = (int)float.Parse(splitLine [7]);

                ImproperTorsion improperTorsion = new ImproperTorsion(t0, t1, t2, t3, v, gamma, periodicity);
                parameters.improperTorsions.Add(improperTorsion);
            }
        }

        return(parameters);
    }
Exemple #31
0
 public void SetStretch(Stretch stretch)
 {
     SourceImage.Stretch = stretch;
 }
Exemple #32
0
    public bool AreNeighbours(Node a, Node b)
    {
        Stretch st = GetStretch(a, b);

        return(st != null);
    }
Exemple #33
0
        public async Task MeasureSource_Expected_Result(
            Stretch stretch,
            string alignment,
            double imageNaturalWidth,
            double imageNaturalHeight,
            double finalWidth,
            double finalHeight,
            double expectedX,
            double expectedY,
            double expectedWidth,
            double expectedHeight)
        {
            var imageNaturalSize           = new Size(imageNaturalWidth, imageNaturalHeight);
            var finalSize                  = new Size(finalWidth, finalHeight);
            var expectedRect               = new Rect(expectedX, expectedY, expectedWidth, expectedHeight);
            HorizontalAlignment horizontal = default;
            VerticalAlignment   vertical   = default;

            switch (alignment[0])
            {
            case 'l':
                horizontal = HorizontalAlignment.Left;
                break;

            case 'c':
                horizontal = HorizontalAlignment.Center;
                break;

            case 'r':
                horizontal = HorizontalAlignment.Right;
                break;

            case 's':
                horizontal = HorizontalAlignment.Stretch;
                break;
            }
            switch (alignment[1])
            {
            case 't':
                vertical = VerticalAlignment.Top;
                break;

            case 'c':
                vertical = VerticalAlignment.Center;
                break;

            case 'b':
                vertical = VerticalAlignment.Bottom;
                break;

            case 's':
                vertical = VerticalAlignment.Stretch;
                break;
            }

            var image = new Image {
                Stretch = stretch, HorizontalAlignment = horizontal, VerticalAlignment = vertical
            };

            var containerRect = image.MeasureSource(finalSize, imageNaturalSize);
            var measuredRect  = image.ArrangeSource(finalSize, containerRect);

            measuredRect.Should().Be(
                expectedRect,
                $"Invalid output for image size {imageNaturalSize} when finalSize is {finalSize} using stretch {stretch} alignment {horizontal}/{vertical}");
        }
 public ImageButton(PlatformBitmap bitmap, Stretch stretch, PlatformBitmap focusedBitmap)
     : this(bitmap, stretch)
 {
     Control.FocusedBitmap = focusedBitmap;
 }
 public void Operators()
 {
     Assert.IsTrue(Stretch.Between(TestData.Stockholm, TestData.Wellington) == Stretch.Between(TestData.Stockholm, TestData.Wellington));
     Assert.IsFalse(Stretch.Between(TestData.Stockholm, TestData.Wellington) == Stretch.Between(TestData.Hövik, TestData.Höviksnäs));
     Assert.IsFalse(Stretch.Between(TestData.Stockholm, TestData.Wellington) != Stretch.Between(TestData.Stockholm, TestData.Wellington));
     Assert.IsTrue(Stretch.Between(TestData.Stockholm, TestData.Wellington) != Stretch.Between(TestData.Hövik, TestData.Höviksnäs));
 }
Exemple #36
0
        public UIGraphic AddPaths(
            double x, double y,
            double width, double height,
            string[] paths,
            double contentX, double contentY,
            double contentWidth, double contentHeight,
            CCColor4B fill, CCColor4B stroke,
            double strokeThickness = 1,
            Stretch stretch = Stretch.StretchFill
        )
        {
            if (width == 0) width = contentWidth;
            if (height == 0) height = contentHeight;

            double scalex = 1.0;
            double scaley = 1.0;
            //if (stretch == Stretch.StretchNone) { } else
            if (stretch == Stretch.StretchFill)
            {
                if (width != contentWidth || height != contentHeight)
                {
                    scalex = width / contentWidth;
                    scaley = height / contentHeight;
                }
            }
            else if (stretch == Stretch.StretchUniformToFill)
            {
                scalex = scaley = Math.Min(width / contentWidth, height / contentHeight);
            }

            foreach (string path in paths)
            {
                IVertexSource vertexs = MiniLanguage.CreatePathStorage(path);

                //先缩放再平移
                if (scalex != 1.0 || scaley != 1.0)
                    vertexs = new VertexSourceApplyTransform(vertexs, Affine.NewScaling(scalex, scaley));

                if (x != 0 || y != 0 || contentX != 0 || contentY != 0)
                    vertexs = new VertexSourceApplyTransform(vertexs, Affine.NewTranslation(x - contentX, y - contentY));

                if (fill.A > 0) this.graphics2D.Render(vertexs, new RGBA_Bytes(fill.R, fill.G, fill.B, fill.A));
                if (stroke.A > 0) this.graphics2D.Render(new Stroke(vertexs, strokeThickness), new RGBA_Bytes(stroke.R, stroke.G, stroke.B, stroke.A));
            }

            return this;
        }
Exemple #37
0
        private static Size ComputeScaleFactor(Size availableSize, Size contentSize, Stretch stretch, StretchDirection stretchDirection) {
            var unlimitedWidth = double.IsPositiveInfinity(availableSize.Width);
            var unlimitedHeight = double.IsPositiveInfinity(availableSize.Height);
            if (stretch != Stretch.Uniform && stretch != Stretch.UniformToFill && stretch != Stretch.Fill || unlimitedWidth && unlimitedHeight) {
                return new Size(1d, 1d);
            }

            var scaleX = Equals(contentSize.Width, 0d) ? 0.0 : availableSize.Width / contentSize.Width;
            var scaleY = Equals(contentSize.Height, 0d) ? 0.0 : availableSize.Height / contentSize.Height;
            if (unlimitedWidth) {
                scaleX = scaleY;
            } else if (unlimitedHeight) {
                scaleY = scaleX;
            } else {
                switch (stretch) {
                    case Stretch.Uniform:
                        scaleX = scaleY = scaleX < scaleY ? scaleX : scaleY;
                        break;
                    case Stretch.UniformToFill:
                        scaleX = scaleY = scaleX > scaleY ? scaleX : scaleY;
                        break;
                    case Stretch.Fill:
                        break;
                }
            }

            switch (stretchDirection) {
                case StretchDirection.UpOnly:
                    if (scaleX < 1.0) scaleX = 1.0;
                    if (scaleY < 1.0) scaleY = 1.0;
                    break;
                case StretchDirection.DownOnly:
                    if (scaleX > 1.0) scaleX = 1.0;
                    if (scaleY > 1.0) scaleY = 1.0;
                    break;
                case StretchDirection.Both:
                    break;
            }

            return new Size(scaleX, scaleY);
        }
Exemple #38
0
 private void OnStretchChanged(Stretch newValue, Stretch oldValue)
 {
     ApplyStretch();
 }
 public ImageButton(PlatformBitmap bitmap, Stretch stretch)
     : this()
 {
     Control.Bitmap = bitmap;
     Control.Stretch = stretch;
 }
        /// <summary>
        /// Instructs the media to stretch using the given Stretch mode.
        /// </summary>
        public void SetStretch(Stretch stretch)
        {
            DebugTrace("[SetStretch] {0}", stretch);
            VerifyNotDisposed();

            SetStretchCore(stretch);
        }
 public ImageButton(PlatformBitmap bitmap, Stretch stretch, PlatformBitmap focusedBitmap, PlatformBitmap clickedBitmap)
     : this(bitmap, stretch, focusedBitmap)
 {
     Control.ClickedBitmap = clickedBitmap;
 }
    protected static float NormalizeOutputSizeToImageSize(SizeF imageSize, SizeF outputSize, Stretch stretch)
    {
      // Calculate zoom for best fit (largest image length (X/Y) fits completely in output area)
      float zoomFactorX = imageSize.Width / outputSize.Width;
      float zoomFactorY = imageSize.Height / outputSize.Height;

      return zoomFactorX > zoomFactorY == (stretch == Stretch.Uniform) ? zoomFactorX : zoomFactorY;
    }
Exemple #43
0
 private void StretchPropertyChanged(Stretch stretch)
 {
     internalImage.Stretch = stretch;
 }
 /// <summary>
 /// Renders this image source to the client area using the passed <paramref name="renderContext"/>.
 /// </summary>
 /// <param name="renderContext">The current rendering context</param>
 /// <param name="stretchMode">The mode of stretching to perform when the image doesn't fit the client area.</param>
 /// <param name="stretchDirection">The condition required for stretching to take place.</param>
 public abstract void Render(RenderContext renderContext, Stretch stretchMode, StretchDirection stretchDirection);
        public void MinAngle()
        {
            var s = Stretch.Between(TestData.Hövik, TestData.Höviksnäs);

            Assert.AreEqual(Angle.FromDegrees(173.471107), s.MinAngle(Position.FromDegrees(58.033296, 11.750197)));
        }
Exemple #46
0
 public static void SetStretch(DependencyObject dependencyObject, Stretch stretch)
 {
     dependencyObject.SetValue(StretchProperty, stretch);
 }
 protected virtual void SetStretchCore(Stretch stretch)
 {
     _mediaElement.Stretch = stretch;
 }
Exemple #48
0
 public void UpdateAspect(Stretch aspect)
 {
     _aspect = aspect;
     Invalidate();
 }
    /// <summary>
    /// This is a helper provided to assist derived Sources when scaling their content to
    /// the owner size.
    /// </summary>
    /// <param name="target">The total available space.</param>
    /// <param name="source">The unscaled source size.</param>
    /// <param name="stretchMode">The <see cref="Stretch"/> mode that determines which stretching technique to use.</param>
    /// <param name="direction">The <see cref="StretchDirection"/> that determines when to perform scaling.</param>
    /// <returns>The scaled source size, which may be larger than the <paramref name="target"/> size.</returns>
    public SizeF StretchSource(SizeF target, SizeF source, Stretch stretchMode, StretchDirection direction)
    {
      if (direction == StretchDirection.DownOnly && source.Width <= target.Width && source.Height <= target.Height)
        return source;
      if (direction == StretchDirection.UpOnly && source.Width >= target.Width && source.Height >= target.Height)
        return source;

      switch (stretchMode)
      {
        case Stretch.None:
          // Original size
          break;
        case Stretch.Fill:
          // Stretch to fit
          source = target;
          break;
        case Stretch.Uniform:
          // Keep aspect ratio and show borders
          {
            float ratio = System.Math.Min(target.Width / source.Width, target.Height / source.Height);
            source.Width *= ratio;
            source.Height *= ratio;
          }
          break;
        case Stretch.UniformToFill:
          // Keep aspect ratio, zoom in to avoid borders
          {
            float ratio = System.Math.Max(target.Width / source.Width, target.Height / source.Height);
            source.Width *= ratio;
            source.Height *= ratio;
          }
          break;
      }
      return source;
    }
Exemple #50
0
 partial void OnStretchChanged(Stretch newValue, Stretch oldValue);
 protected override void SetStretchCore(Stretch stretch)
 {
     Image.Stretch = stretch;
 }
Exemple #52
0
        public static Stretch Unbox_Stretch(IntPtr val)
        {
            Stretch ret = (Stretch)NoesisGUI_PINVOKE.Unbox_Stretch(val);

            return(ret);
        }
 public override void Render(RenderContext renderContext, Stretch stretchMode, StretchDirection stretchDirection)
 {
   if (!IsAllocated)
     return;
   SizeF rawSourceSize = RawSourceSize;
   SizeF modifiedSourceSize = StretchSource(_imageContext.RotatedFrameSize, rawSourceSize, stretchMode, stretchDirection);
   Vector4 frameData = new Vector4(rawSourceSize.Width, rawSourceSize.Height, (float) EffectTimer, 0);
   if (_primitiveBuffer != null && _imageContext.StartRender(renderContext, modifiedSourceSize, Texture, TextureClip, BorderColor, frameData))
   {
     _primitiveBuffer.Render(0);
     _imageContext.EndRender();
   }
 }
Exemple #54
0
        public static IntPtr Box_Stretch(Stretch val)
        {
            IntPtr ret = NoesisGUI_PINVOKE.Box_Stretch((int)val);

            return(ret);
        }
 unsafe internal static extern void MilUtility_GetTileBrushMapping(
     D3DMATRIX* transform,
     D3DMATRIX* relativeTransform,
     Stretch stretch, 
     AlignmentX alignmentX,
     AlignmentY alignmentY, 
     BrushMappingMode viewPortUnits, 
     BrushMappingMode viewBoxUnits,
     Rect* shapeFillBounds, 
     Rect* contentBounds,
     ref Rect viewport,
     ref Rect viewbox,
     out D3DMATRIX contentToShape, 
     out int brushIsEmpty
     ); 
Exemple #56
0
        protected override void OnStretchUpdated(Stretch newValue)
        {
            base.OnStretchUpdated(newValue);

            InvalidateMeasure();
        }
Exemple #57
0
 protected virtual void OnStretchChanged(Stretch oldValue, Stretch newValue)
 {
     ReadOnlyCollection<DependencyObject> itemContainers = this.ItemContainerManager.GetContainerList();
     if (itemContainers.Count > 0)
     {
         foreach (object itemContainer in itemContainers)
         {
             ImageListViewItem imageListViewItem = itemContainer as ImageListViewItem;
             imageListViewItem.Stretch = newValue;
         }
     }
 }
Exemple #58
0
 public static void SetImageStretch(DependencyObject obj, Stretch value)
 {
     obj.SetValue(ImageStretchProperty, value);
 }
Exemple #59
0
        private static Vector CalculateScaling(Size availableSize, Size imageSize, Stretch stretch)
        {
            double scaleX = 1;
            double scaleY = 1;

            if (stretch != Stretch.None)
            {
                scaleX = availableSize.Width / imageSize.Width;
                scaleY = availableSize.Height / imageSize.Height;

                switch (stretch)
                {
                    case Stretch.Uniform:
                        scaleX = scaleY = Math.Min(scaleX, scaleY);
                        break;
                    case Stretch.UniformToFill:
                        scaleX = scaleY = Math.Max(scaleX, scaleY);
                        break;
                }
            }

            return new Vector(scaleX, scaleY);
        }
Exemple #60
0
        internal static (Size, Matrix) CalculateSizeAndTransform(Size availableSize, Rect shapeBounds, Stretch Stretch)
        {
            Size   shapeSize = new Size(shapeBounds.Right, shapeBounds.Bottom);
            Matrix translate = Matrix.Identity;
            double desiredX  = availableSize.Width;
            double desiredY  = availableSize.Height;
            double sx        = 0.0;
            double sy        = 0.0;

            if (Stretch != Stretch.None)
            {
                shapeSize = shapeBounds.Size;
                translate = Matrix.CreateTranslation(-(Vector)shapeBounds.Position);
            }

            if (double.IsInfinity(availableSize.Width))
            {
                desiredX = shapeSize.Width;
            }

            if (double.IsInfinity(availableSize.Height))
            {
                desiredY = shapeSize.Height;
            }

            if (shapeBounds.Width > 0)
            {
                sx = desiredX / shapeSize.Width;
            }

            if (shapeBounds.Height > 0)
            {
                sy = desiredY / shapeSize.Height;
            }

            if (double.IsInfinity(availableSize.Width))
            {
                sx = sy;
            }

            if (double.IsInfinity(availableSize.Height))
            {
                sy = sx;
            }

            switch (Stretch)
            {
            case Stretch.Uniform:
                sx = sy = Math.Min(sx, sy);
                break;

            case Stretch.UniformToFill:
                sx = sy = Math.Max(sx, sy);
                break;

            case Stretch.Fill:
                if (double.IsInfinity(availableSize.Width))
                {
                    sx = 1.0;
                }

                if (double.IsInfinity(availableSize.Height))
                {
                    sy = 1.0;
                }

                break;

            default:
                sx = sy = 1;
                break;
            }

            var transform = translate * Matrix.CreateScale(sx, sy);
            var size      = new Size(shapeSize.Width * sx, shapeSize.Height * sy);

            return(size, transform);
        }