コード例 #1
0
ファイル: MyCanvas.cs プロジェクト: dfr0/moon
	public void PageLoaded (object sender, EventArgs e) {

		Rectangle reflected = FindName ("Reflected") as Rectangle;
		Canvas c = FindName ("Normal") as Canvas;

		VisualBrush vb = new VisualBrush ();
		TransformGroup tg = new TransformGroup ();

		MatrixTransform mt = new MatrixTransform ();
		mt.Matrix = new Matrix (1, 0, 0, -1, 0, 0);
		tg.Children.Add (mt);

		TranslateTransform tt = new TranslateTransform ();
		tt.Y = c.Height;
		tg.Children.Add (tt);

		vb.Transform = tg;

		vb.Visual = c;

		reflected.Fill = vb;
	}
コード例 #2
0
        public ColorPicker()
        {
            InitializeComponent();

            var indexMap = new int[]
            {
                1, 4, 7, 10, 13, 16,
                18, 3, 6, 9, 12, 15,
                2, 5, 8, 11, 14, 17
            };

            for (int i = 0; i < 18; i++)
            {
                var pgeom = new PathGeometry();
                var fig   = new PathFigure();
                fig.StartPoint = new Point();
                fig.IsClosed   = true;
                fig.IsFilled   = true;
                fig.Segments.Add(new LineSegment(new Point(), true));
                fig.Segments.Add(new LineSegment(new Point(), true));
                pgeom.Figures.Add(fig);
                var bIndex = indexMap[i];
                var brush  = new SolidColorBrush((Color)Application.Current.Resources[$"Color{bIndex:D2}"]);
                var path   = new Path();
                path.Fill   = brush;
                path.Stroke = new SolidColorBrush(Color.Multiply(brush.Color, 0.6f));
                path.Data   = pgeom;
                var tg = new TransformGroup();
                tg.Children.Add(new TranslateTransform());
                tg.Children.Add(new RotateTransform());
                path.RenderTransform = tg;

                if (i < 6)
                {
                    Panel.SetZIndex(path, 1);
                }

                path.IsHitTestVisible = false;
                canvas.Children.Add(path);
                path.MouseEnter          += ColorOptionMouseEnter;
                path.MouseLeave          += ColorOptionMouseLeave;
                path.MouseLeftButtonDown += ColorOptionMouseLBDown;
                path.MouseLeftButtonUp   += ColorOptionMouseLBUp;
                _colorOptionsShape[i]     = path;
                path.Cursor = Cursors.Hand;
                path.Tag    = i;
            }


            _centerPolygon.Points.Add(new Point());
            _centerPolygon.Points.Add(new Point());
            _centerPolygon.Points.Add(new Point());
            _centerPolygon.Points.Add(new Point());
            _centerPolygon.Points.Add(new Point());
            _centerPolygon.Points.Add(new Point());
            _centerPolygon.Fill            = new SolidColorBrush();
            _centerPolygon.Stroke          = new SolidColorBrush();
            _centerPolygon.StrokeThickness = 2.0;
            _centerPolygon.Cursor          = Cursors.Hand;
            Panel.SetZIndex(_centerPolygon, 2);

            _centerPolygon.MouseEnter          += HexMouseEnter;
            _centerPolygon.MouseLeave          += HexMouseLeave;
            _centerPolygon.MouseLeftButtonDown += HexMouseLButtonDown;
            _centerPolygon.MouseLeftButtonUp   += HexMouseLButtonUp;

            canvas.Children.Add(_centerPolygon);

            OnRadiusChanged(this, new DependencyPropertyChangedEventArgs(RadiusProperty, 0, Radius));
            OnPickedColorIndexChanged(this, new DependencyPropertyChangedEventArgs(PickedColorIndexProperty, 0, 0));
        }
コード例 #3
0
        private Transform UseFitToViewbox(SvgElement svgElement, Rect elementBounds)
        {
            if (svgElement == null)
            {
                return(null);
            }
            ISvgFitToViewBox fitToView = svgElement as ISvgFitToViewBox;

            if (fitToView == null)
            {
                return(null);
            }

            SvgPreserveAspectRatio spar = (SvgPreserveAspectRatio)fitToView.PreserveAspectRatio.AnimVal;

            SvgRect viewBox   = (SvgRect)fitToView.ViewBox.AnimVal;
            SvgRect rectToFit = new SvgRect(elementBounds.X, elementBounds.Y, elementBounds.Width, elementBounds.Height);

            double[] transformArray = spar.FitToViewBox(viewBox, rectToFit);

            double translateX = Math.Round(transformArray[0], 4);
            double translateY = Math.Round(transformArray[1], 4);
            double scaleX     = Math.Round(transformArray[2], 4);
            double scaleY     = Math.Round(transformArray[3], 4);

            Transform translateMatrix = null;
            Transform scaleMatrix     = null;

            if (!translateX.Equals(0.0) || !translateY.Equals(0.0))
            {
                translateMatrix = new TranslateTransform(translateX, translateY);
            }
            if (!scaleX.Equals(1.0) || !scaleY.Equals(1.0))
            {
                scaleMatrix = new ScaleTransform(scaleX, scaleY);
            }

            if (translateMatrix != null && scaleMatrix != null)
            {
                // Create a TransformGroup to contain the transforms
                // and add the transforms to it.
                if (translateMatrix.Value.IsIdentity && scaleMatrix.Value.IsIdentity)
                {
                    return(null);
                }
                if (translateMatrix.Value.IsIdentity)
                {
                    return(scaleMatrix);
                }
                if (scaleMatrix.Value.IsIdentity)
                {
                    return(translateMatrix);
                }
                TransformGroup transformGroup = new TransformGroup();
                transformGroup.Children.Add(scaleMatrix);
                transformGroup.Children.Add(translateMatrix);

                return(transformGroup);
            }
            if (translateMatrix != null)
            {
                return(translateMatrix);
            }
            if (scaleMatrix != null)
            {
                return(scaleMatrix);
            }
            return(null);
        }
コード例 #4
0
        public Train(Canvas canvas, Config config, BitmapImage[] images)
        {
            wagons = new Image[config.trainIndexes.Length];

            //Create WPF Image objects (wagons) from supplied Bitmaps
            double maxHeight = 0;

            for (int i = 0; i < config.trainIndexes.Length; i++)
            {
                BitmapImage bitmap;
                if (config.trainIndexes[i] >= config.wagonSources.Length || config.trainIndexes[i] < 0)
                {
                    //index out of bounds, use "wrong index" texture instead
                    using (var ms = new System.IO.MemoryStream(Properties.Resources.WrongIndex))
                    {
                        bitmap = new BitmapImage();
                        bitmap.BeginInit();
                        bitmap.CacheOption  = BitmapCacheOption.OnLoad;
                        bitmap.StreamSource = ms;
                        bitmap.EndInit();
                    }
                }
                else
                {
                    bitmap = images[config.trainIndexes[i]];
                }

                wagons[i] = new Image()
                {
                    Source = bitmap, Width = config.scale * bitmap.Width / bitmap.Height, Height = config.scale
                };
                wagons[i].RenderTransformOrigin = new Point(0.5, 0.5);
                canvas.Children.Add(wagons[i]);
                Canvas.SetLeft(wagons[i], -wagons[i].Width);

                if (wagons[i].Height > maxHeight)
                {
                    maxHeight = wagons[i].Height;
                }
            }

            path = new Path(canvas.ActualHeight - maxHeight - 10, 10, canvas.ActualWidth);

            //Animation frame loop
            dispatherTimer       = new DispatcherTimer();
            dispatherTimer.Tick += (_, e) =>
            {
                double dist = currentDistance;

                //move each wagon
                foreach (var wagon in wagons)
                {
                    Point pointBack;
                    Point pointFront;

                    if (right)
                    {
                        pointBack  = path.GetPoint(dist - wagon.Width);
                        pointFront = path.GetPoint(dist);
                    }
                    if (!right)
                    {
                        pointBack    = path.GetPoint(dist);
                        pointFront   = path.GetPoint(dist + wagon.Width);
                        pointFront.X = path.width - pointFront.X;
                        pointBack.X  = path.width - pointBack.X;
                    }

                    Canvas.SetLeft(wagon, pointBack.X);
                    Canvas.SetTop(wagon, pointBack.Y + maxHeight - wagon.Height);

                    double x   = pointFront.X - pointBack.X;
                    double y   = pointFront.Y - pointBack.Y;
                    double sin = y / Math.Sqrt(x * x + y * y);

                    TransformGroup grp = new TransformGroup();

                    if (!right)
                    {
                        grp.Children.Add(new ScaleTransform(-1, 1));
                        grp.Children.Add(new RotateTransform(-Math.Asin(sin) / Math.PI * 180, wagon.Width / 2, wagon.Height / 2));
                    }
                    else
                    {
                        grp.Children.Add(new RotateTransform(Math.Asin(sin) / Math.PI * 180, -wagon.Width / 2, wagon.Height / 2));
                    }
                    wagon.RenderTransform = grp;
                    dist -= wagon.Width;
                }

                //check if first wagon has finished it's trip
                if (!firstFinished && currentDistance > path.length)
                {
                    firstFinished = true;
                    if (onFirstFinished != null)
                    {
                        onFirstFinished(null, new FinishedEventArgs(path.GetToTop()));
                    }
                }

                //check if the last wagon has finished it's trip
                if (dist > path.length)
                {
                    dispatherTimer.Stop();
                    if (onLastFinished != null)
                    {
                        onLastFinished(null, new FinishedEventArgs(path.GetToTop()));
                    }
                }

                currentDistance += speed / config.framerate;
            };
            dispatherTimer.Interval = TimeSpan.FromMilliseconds(1000d / config.framerate);
        }
コード例 #5
0
        /// <summary>
        /// Draws text.
        /// </summary>
        /// <param name="p">The position.</param>
        /// <param name="text">The text.</param>
        /// <param name="fill">The text color.</param>
        /// <param name="fontFamily">The font family.</param>
        /// <param name="fontSize">Size of the font (in device independent units, 1/96 inch).</param>
        /// <param name="fontWeight">The font weight.</param>
        /// <param name="rotate">The rotation angle.</param>
        /// <param name="halign">The horizontal alignment.</param>
        /// <param name="valign">The vertical alignment.</param>
        /// <param name="maxSize">The maximum size of the text (in device independent units, 1/96 inch).</param>
        public void DrawText(
            ScreenPoint p,
            string text,
            OxyColor fill,
            string fontFamily,
            double fontSize,
            double fontWeight,
            double rotate,
            HorizontalAlignment halign,
            VerticalAlignment valign,
            OxySize?maxSize)
        {
            var tb = this.CreateAndAdd <TextBlock>();

            tb.Text       = text;
            tb.Foreground = this.GetCachedBrush(fill);
            if (fontFamily != null)
            {
                tb.FontFamily = this.GetCachedFontFamily(fontFamily);
            }

            if (fontSize > 0)
            {
                tb.FontSize = fontSize;
            }

            if (fontWeight > 0)
            {
                tb.FontWeight = GetFontWeight(fontWeight);
            }

            TextOptions.SetTextFormattingMode(tb, this.TextFormattingMode);

            double dx = 0;
            double dy = 0;

            if (maxSize != null || halign != HorizontalAlignment.Left || valign != VerticalAlignment.Top)
            {
                tb.Measure(new Size(1000, 1000));
                var size = tb.DesiredSize;
                if (maxSize != null)
                {
                    if (size.Width > maxSize.Value.Width + 1e-3)
                    {
                        size.Width = Math.Max(maxSize.Value.Width, 0);
                    }

                    if (size.Height > maxSize.Value.Height + 1e-3)
                    {
                        size.Height = Math.Max(maxSize.Value.Height, 0);
                    }

                    tb.Width  = size.Width;
                    tb.Height = size.Height;
                }

                if (halign == HorizontalAlignment.Center)
                {
                    dx = -size.Width / 2;
                }

                if (halign == HorizontalAlignment.Right)
                {
                    dx = -size.Width;
                }

                if (valign == VerticalAlignment.Middle)
                {
                    dy = -size.Height / 2;
                }

                if (valign == VerticalAlignment.Bottom)
                {
                    dy = -size.Height;
                }
            }

            var transform = new TransformGroup();

            transform.Children.Add(new TranslateTransform(dx, dy));
            if (Math.Abs(rotate) > double.Epsilon)
            {
                transform.Children.Add(new RotateTransform(rotate));
            }

            transform.Children.Add(new TranslateTransform(p.X, p.Y));
            tb.RenderTransform = transform;
            if (tb.Clip != null)
            {
                tb.Clip.Transform = tb.RenderTransform.Inverse as Transform;
            }

            tb.SetValue(RenderOptions.ClearTypeHintProperty, ClearTypeHint.Enabled);
        }
コード例 #6
0
ファイル: ShowElement.cs プロジェクト: xuming1985/WPFApp
        public void AddItem(UIElement item)
        {
            Contract.Requires <ArgumentNullException>(item != null);
            Debug.Assert(VisualTreeHelper.GetParent(item) == null, "item", "item should not have a parent");

            m_elements.Add(item);
            this.AddVisualChild(item);
            this.InvalidateMeasure();

            item.RenderTransformOrigin = new Point(.5, .5);

            TransformGroup group = new TransformGroup();

            group.Children.Add(new ScaleTransform(.6, .6));
            ScaleTransform animatedScale = new ScaleTransform();

            group.Children.Add(animatedScale);

            RotateTransform rotateTransform = new RotateTransform();

            group.Children.Add(rotateTransform);

            group.Children.Add(new TranslateTransform());

            item.RenderTransform = group;

            if (m_elements.Count >= c_maxCount)
            {
                int oldestCount = m_elements.Count - c_maxCount;

                for (int i = 0; i < oldestCount; i++)
                {
                    UIElement oldest = m_elements[0];
                    m_fadingElements.Add(oldest);
                    m_elements.RemoveAt(0);

                    DoubleAnimation fadeOut = GetFadeOutAnimation();

                    fadeOut.Completed += delegate(object sender, EventArgs e)
                    {
                        m_fadingElements.Remove(oldest);
                        this.RemoveVisualChild(oldest);
                    };

                    oldest.BeginAnimation(UIElement.OpacityProperty, fadeOut);
                }
            }

            DoubleAnimation rotationAnimation = GetRandomRotateAnimation();

            rotateTransform.BeginAnimation(RotateTransform.AngleProperty, rotationAnimation);

            DoubleAnimation fadeIn = GetFadeInAnimation();

            item.BeginAnimation(UIElement.OpacityProperty, fadeIn);

            DoubleAnimation shrink = GetShrinkAnimation();

            animatedScale.BeginAnimation(ScaleTransform.ScaleXProperty, shrink);
            animatedScale.BeginAnimation(ScaleTransform.ScaleYProperty, shrink);
        }
コード例 #7
0
        private Brush GetLinearGradientBrush(SvgLinearGradientElement res, Transform viewBoxTransform = null)
        {
            GradientStopCollection gradientStops = GetGradientStops(res.Stops);

            if (gradientStops == null || gradientStops.Count == 0)
            {
                return(null);
            }

            double x1 = res.X1.AnimVal.Value;
            double x2 = res.X2.AnimVal.Value;
            double y1 = res.Y1.AnimVal.Value;
            double y2 = res.Y2.AnimVal.Value;

            LinearGradientBrush brush = new LinearGradientBrush(gradientStops,
                                                                new Point(x1, y1), new Point(x2, y2));

            SvgSpreadMethod spreadMethod = SvgSpreadMethod.Pad;

            if (res.SpreadMethod != null)
            {
                spreadMethod = (SvgSpreadMethod)res.SpreadMethod.AnimVal;

                if (spreadMethod != SvgSpreadMethod.None)
                {
                    brush.SpreadMethod = WpfConvert.ToSpreadMethod(spreadMethod);
                }
            }

            SvgUnitType mappingMode = SvgUnitType.ObjectBoundingBox;

            if (res.GradientUnits != null)
            {
                mappingMode = (SvgUnitType)res.GradientUnits.AnimVal;
                if (mappingMode == SvgUnitType.ObjectBoundingBox)
                {
                    brush.MappingMode = BrushMappingMode.RelativeToBoundingBox;
                }
                else if (mappingMode == SvgUnitType.UserSpaceOnUse)
                {
                    brush.MappingMode = BrushMappingMode.Absolute;

                    _isUserSpace = true;
                }
            }

            string colorInterpolation = res.GetPropertyValue("color-interpolation");

            if (!string.IsNullOrWhiteSpace(colorInterpolation))
            {
                if (string.Equals(colorInterpolation, "linearRGB", StringComparison.OrdinalIgnoreCase))
                {
                    brush.ColorInterpolationMode = ColorInterpolationMode.ScRgbLinearInterpolation;
                }
                else
                {
                    brush.ColorInterpolationMode = ColorInterpolationMode.SRgbLinearInterpolation;
                }
            }

            MatrixTransform transform = GetTransformMatrix(res);

            if (transform != null && !transform.Matrix.IsIdentity)
            {
                if (viewBoxTransform != null && !viewBoxTransform.Value.IsIdentity)
                {
                    TransformGroup group = new TransformGroup();
                    group.Children.Add(viewBoxTransform);
                    group.Children.Add(transform);

                    brush.Transform = group;
                }
                else
                {
                    brush.Transform = transform;
                }
            }
            else
            {
                float fLeft   = (float)res.X1.AnimVal.Value;
                float fRight  = (float)res.X2.AnimVal.Value;
                float fTop    = (float)res.Y1.AnimVal.Value;
                float fBottom = (float)res.Y2.AnimVal.Value;

                if (mappingMode == SvgUnitType.ObjectBoundingBox)
                {
                    if (!fTop.Equals(fBottom) && !fLeft.Equals(fRight))
                    {
                        var drawingBrush = new DrawingBrush();
                        drawingBrush.Stretch = Stretch.Fill;
                        drawingBrush.Viewbox = new Rect(0, 0, 1, 1);
                        var DrawingRect = new GeometryDrawing(brush, null, new RectangleGeometry(new Rect(0, 0, 1, 1)));
                        drawingBrush.Drawing = DrawingRect;
                        return(drawingBrush);
                    }
                }

                if (fTop.Equals(fBottom))
                {
                }
                else
                {
                    if (fLeft.Equals(fRight))
                    {
                    }
                    else
                    {
                        if (fLeft < fRight)
                        {
                            if (viewBoxTransform != null && !viewBoxTransform.Value.IsIdentity)
                            {
                                brush.Transform = viewBoxTransform;
                            }
                        }
                        else
                        {
                            if (viewBoxTransform != null && !viewBoxTransform.Value.IsIdentity)
                            {
                                brush.Transform = viewBoxTransform;
                            }
                        }
                    }
                }
            }

            return(brush);
        }
コード例 #8
0
ファイル: RenderContext.cs プロジェクト: huoxudong125/oxyplot
        /// <summary>
        /// Draws the text.
        /// </summary>
        /// <param name="p">The position.</param>
        /// <param name="text">The text.</param>
        /// <param name="fill">The fill color.</param>
        /// <param name="fontFamily">The font family.</param>
        /// <param name="fontSize">Size of the font.</param>
        /// <param name="fontWeight">The font weight.</param>
        /// <param name="rotate">The rotation angle.</param>
        /// <param name="halign">The horizontal alignment.</param>
        /// <param name="valign">The vertical alignment.</param>
        /// <param name="maxSize">The maximum size of the text.</param>
        public void DrawText(
            ScreenPoint p,
            string text,
            OxyColor fill,
            string fontFamily,
            double fontSize,
            double fontWeight,
            double rotate,
            OxyPlot.HorizontalAlignment halign,
            OxyPlot.VerticalAlignment valign,
            OxySize? maxSize)
        {
            var tb = new TextBlock { Text = text, Foreground = new SolidColorBrush(fill.ToColor()) };

            // tb.SetValue(TextOptions.TextHintingModeProperty, TextHintingMode.Animated);
            if (fontFamily != null)
            {
                tb.FontFamily = new FontFamily(fontFamily);
            }

            if (fontSize > 0)
            {
                tb.FontSize = fontSize;
            }

            tb.FontWeight = GetFontWeight(fontWeight);

            tb.Measure(new Size(1000, 1000));
            var size = new Size(tb.ActualWidth, tb.ActualHeight);
            if (maxSize != null)
            {
                if (size.Width > maxSize.Value.Width)
                {
                    size.Width = maxSize.Value.Width;
                }

                if (size.Height > maxSize.Value.Height)
                {
                    size.Height = maxSize.Value.Height;
                }

                tb.Clip = new RectangleGeometry { Rect = new Rect(0, 0, size.Width, size.Height) };
            }

            double dx = 0;
            if (halign == OxyPlot.HorizontalAlignment.Center)
            {
                dx = -size.Width / 2;
            }

            if (halign == OxyPlot.HorizontalAlignment.Right)
            {
                dx = -size.Width;
            }

            double dy = 0;
            if (valign == OxyPlot.VerticalAlignment.Middle)
            {
                dy = -size.Height / 2;
            }

            if (valign == OxyPlot.VerticalAlignment.Bottom)
            {
                dy = -size.Height;
            }

            var transform = new TransformGroup();
            transform.Children.Add(new TranslateTransform { X = (int)dx, Y = (int)dy });
            if (!rotate.Equals(0))
            {
                transform.Children.Add(new RotateTransform { Angle = rotate });
            }

            transform.Children.Add(new TranslateTransform { X = (int)p.X, Y = (int)p.Y });
            tb.RenderTransform = transform;
            this.ApplyTooltip(tb);

            if (this.clip)
            {
                // add a clipping container that is not rotated
                var c = new Canvas();
                c.Children.Add(tb);
                this.Add(c);
            }
            else
            {
                this.Add(tb);
            }
        }
コード例 #9
0
        private void AnimateChild(bool reverse)
        {
            var    sineEase = new SineEase();
            double translateCoordinateFrom = 0d;

            string direction = string.Empty;

            switch (this.PlacementDirection)
            {
            case EnumPlacementDirection.Left:
                direction = "X";
                translateCoordinateFrom = 80;
                break;

            case EnumPlacementDirection.Right:
                direction = "X";
                translateCoordinateFrom = -80;
                break;

            case EnumPlacementDirection.Top:
                translateCoordinateFrom = 80;
                direction = "Y";
                break;

            case EnumPlacementDirection.Bottom:
                translateCoordinateFrom = -80;
                direction = "Y";
                break;
            }

            var translateCoordinatePath = string.Format("(UIElement.RenderTransform).(TransformGroup.Children)[1].(TranslateTransform.{0})", direction);

            for (int i = 0; i < this.Items.Count; i++)
            {
                UIElement element = this.ItemContainerGenerator.ContainerFromIndex(i) as UIElement;

                if (element == null)
                {
                    continue;
                }

                var elementTranslateCoordinateFrom = translateCoordinateFrom * i;
                var translateTransform             = new TranslateTransform(
                    this.ItemOrientation == Orientation.Horizontal ? translateCoordinateFrom : 0,
                    this.ItemOrientation == Orientation.Horizontal ? 0 : translateCoordinateFrom);

                var transformGroup = new TransformGroup
                {
                    Children = new TransformCollection(new Transform[]
                    {
                        new ScaleTransform(0, 0),
                        translateTransform
                    })
                };
                element.SetCurrentValue(RenderTransformOriginProperty, new Point(.5, .5));
                element.RenderTransform = transformGroup;

                var deferredStart = i * 20;
                var deferredEnd   = deferredStart + 150.0;

                var absoluteZeroKeyTime  = KeyTime.FromPercent(0.0);
                var deferredStartKeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(deferredStart));
                var deferredEndKeyTime   = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(deferredEnd));

                var opacityAnimation = new DoubleAnimationUsingKeyFrames();
                opacityAnimation.KeyFrames.Add(new EasingDoubleKeyFrame(0, absoluteZeroKeyTime, sineEase));
                opacityAnimation.KeyFrames.Add(new EasingDoubleKeyFrame(0, deferredStartKeyTime, sineEase));
                opacityAnimation.KeyFrames.Add(new EasingDoubleKeyFrame(1, deferredEndKeyTime, sineEase));
                Storyboard.SetTargetProperty(opacityAnimation, new PropertyPath("Opacity"));
                Storyboard.SetTarget(opacityAnimation, element);

                var scaleXAnimation = new DoubleAnimationUsingKeyFrames();
                scaleXAnimation.KeyFrames.Add(new EasingDoubleKeyFrame(0, absoluteZeroKeyTime, sineEase));
                scaleXAnimation.KeyFrames.Add(new EasingDoubleKeyFrame(0, deferredStartKeyTime, sineEase));
                scaleXAnimation.KeyFrames.Add(new EasingDoubleKeyFrame(1, deferredEndKeyTime, sineEase));
                Storyboard.SetTargetProperty(scaleXAnimation, new PropertyPath("(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleX)"));
                Storyboard.SetTarget(scaleXAnimation, element);

                var scaleYAnimation = new DoubleAnimationUsingKeyFrames();
                scaleYAnimation.KeyFrames.Add(new EasingDoubleKeyFrame(0, absoluteZeroKeyTime, sineEase));
                scaleYAnimation.KeyFrames.Add(new EasingDoubleKeyFrame(0, deferredStartKeyTime, sineEase));
                scaleYAnimation.KeyFrames.Add(new EasingDoubleKeyFrame(1, deferredEndKeyTime, sineEase));
                Storyboard.SetTargetProperty(scaleYAnimation, new PropertyPath("(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleY)"));
                Storyboard.SetTarget(scaleYAnimation, element);

                var translateCoordinateAnimation = new DoubleAnimationUsingKeyFrames();
                translateCoordinateAnimation.KeyFrames.Add(new EasingDoubleKeyFrame(elementTranslateCoordinateFrom, absoluteZeroKeyTime, sineEase));
                translateCoordinateAnimation.KeyFrames.Add(new EasingDoubleKeyFrame(elementTranslateCoordinateFrom, deferredStartKeyTime, sineEase));
                translateCoordinateAnimation.KeyFrames.Add(new EasingDoubleKeyFrame(0, deferredEndKeyTime, sineEase));

                Storyboard.SetTargetProperty(translateCoordinateAnimation, new PropertyPath(translateCoordinatePath));
                Storyboard.SetTarget(translateCoordinateAnimation, element);

                var storyboard = new Storyboard();
                storyboard.Children.Add(opacityAnimation);
                storyboard.Children.Add(scaleXAnimation);
                storyboard.Children.Add(scaleYAnimation);
                storyboard.Children.Add(translateCoordinateAnimation);

                if (reverse)
                {
                    storyboard.AutoReverse = true;
                    storyboard.Begin();
                    storyboard.Seek(TimeSpan.FromMilliseconds(deferredEnd));
                    storyboard.Resume();
                }
                else
                {
                    storyboard.Begin();
                }
            }
        }
コード例 #10
0
        private async void InitMainMenu()
        {
            #region 初始化属性
            var mainMenuInfo = _userConfigution.ImageSetting.MainMenuInfo;

            var animatedGif = await GetMainMenuIcon();

            _mainMenu = new UserControl
            {
                Content = animatedGif,
                Width   = mainMenuInfo.Width,
                Height  = mainMenuInfo.Height,
                ToolTip = "EasyImage主菜单",
                Cursor  = Cursors.SizeAll,
            };

            var transformGroup = new TransformGroup();
            transformGroup.Children.Add(new ScaleTransform(1, 1));
            transformGroup.Children.Add(new RotateTransform(0));
            transformGroup.Children.Add(new TranslateTransform(mainMenuInfo.TranslateX, mainMenuInfo.TranslateY));
            _mainMenu.RenderTransform = transformGroup;

            var dragBehavior = new MouseDragElementBehavior <UserControl>
            {
                MoveableRange = new Rect(0, 0, SystemParameters.VirtualScreenWidth, SystemParameters.VirtualScreenHeight),
            };
            dragBehavior.Attach(_mainMenu);

            _autoHideBehavior = new AutoHideElementBehavior
            {
                AutoHideFactor = _userConfigution.WindowState.ImageWindowState.AutoHideFactor,
            };
            _autoHideBehavior.Attach(_mainMenu);

            #endregion

            #region 添加上下文菜单
            var contextMenu = new ContextMenu();
            var item        = new MenuItem {
                Header = "新建", Tag = "New"
            };

            #region 二级菜单
            var subItem = new MenuItem
            {
                Header = "矩形",
                Tag    = "Square"
            };
            subItem.Click += AddImageFromInternal;
            item.Items.Add(subItem);

            subItem = new MenuItem
            {
                Header = "圆形",
                Tag    = "Circle"
            };
            subItem.Click += AddImageFromInternal;
            item.Items.Add(subItem);

            subItem = new MenuItem
            {
                Header = "三角形",
                Tag    = "Triangle"
            };
            subItem.Click += AddImageFromInternal;
            item.Items.Add(subItem);

            subItem = new MenuItem
            {
                Header = "五角星",
                Tag    = "FiveStar"
            };
            subItem.Click += AddImageFromInternal;
            item.Items.Add(subItem);

            subItem = new MenuItem
            {
                Header = "圆环",
                Tag    = "Torus"
            };
            subItem.Click += AddImageFromInternal;
            item.Items.Add(subItem);

            #endregion

            contextMenu.Items.Add(item);

            item = new MenuItem {
                Header = "打开", Tag = "Open"
            };
            item.Click += LoadEasyImageFromFile;
            contextMenu.Items.Add(item);

            item = new MenuItem {
                Header = "添加", Tag = "Add"
            };
            item.Click += AddImagesFromFile;
            contextMenu.Items.Add(item);

            item = new MenuItem {
                Header = "保存", Tag = "Save"
            };
            item.Click += SaveEasyImageToFile;
            contextMenu.Items.Add(item);

            item = new MenuItem {
                Header = "另保存", Tag = "SaveAs"
            };
            item.Click += SaveAsEasyImageToFile;
            contextMenu.Items.Add(item);

            item = new MenuItem {
                Header = "粘贴", Tag = "Paste"
            };
            item.Click += PasteImagesFromClipboard;
            contextMenu.Items.Add(item);

            item = new MenuItem {
                Header = "设置", Tag = "Setting"
            };
            item.Click += SettingWindow;
            contextMenu.Items.Add(item);

            item = new MenuItem {
                Header = "收藏夹", Tag = "Favorites"
            };
            item.Click += (sender, e) =>
            {
                _imageFavoritesWindow.ShowWindow();
            };
            contextMenu.Items.Add(item);

            contextMenu.Items.Add(new Separator());//分割线

            item = new MenuItem {
                Header = "退出", Tag = "Exit"
            };
            item.Click += (sender, args) =>
            {
                Close();
            };
            contextMenu.Items.Add(item);

            _mainMenu.ContextMenu = contextMenu;
            #endregion

            #region 添加事件
            _mainMenu.MouseDown          += MainMenu_MouseDown;
            _mainMenu.ContextMenuOpening += MainMenu_ContextMenuOpening;

            #endregion

            MainCanvas.Children.Add(_mainMenu);
        }
コード例 #11
0
        /*This function displays a node on the screen. It is called only when a node is in the selected state to display its content.
         * Parameters
         * Int16[,] NodeProp- Node location
         * string textColor - Node's text color
         * double top - Top or y coordinate of the cluster location on screen
         * double left - Left or x coordinate of the cluster location on screen
         * Canvas PaintCanvas - The paintcanvas where it is to be displayed
         * int details - this parameter is unused and can be removed
         */
        public void displayNode(Int16[,] NodeProp, string textColor, double top, double left, Canvas PaintCanvas, int details)
        {
            //stop and close any of the videos playing in previously selected node
            MainWindow.mp.Stop();
            MainWindow.mp.Close();

            //Create the ellipse for this node and assign values to its parameters
            Ellipse ellipse = new Ellipse();

            ellipse.Height          = NodeProp[0, 2];
            ellipse.Width           = NodeProp[0, 2];
            ellipse.StrokeThickness = 0;
            BrushConverter bc    = new BrushConverter();
            Brush          brush = (Brush)bc.ConvertFrom(color);

            ImageBrush im  = new ImageBrush();
            Label      img = new Label();

            /*This code finds the previously selected node on the paint canvas and removes any related nodes from it and hides its information content
             * because now another node is being selected for information */
            foreach (FrameworkElement element in MainWindow.PaintCanvas.Children)
            {
                if (element is Grid)
                {
                    Grid g = element as Grid;
                    if (g != null && g.Children.Count > 6)
                    {
                        Ellipse e  = g.Children[0] as Ellipse;
                        Label   l  = new Label();
                        Label   l1 = new Label();
                        l1 = g.Children[6] as Label;
                        Label l2 = g.Children[5] as Label;
                        l = g.Children[7] as Label;
                        Label          l3 = g.Children[4] as Label;
                        BrushConverter BC = new BrushConverter();
                        Brush          b  = (Brush)BC.ConvertFrom(l.Content);
                        TextBlock      t  = g.Children[1] as TextBlock;

                        if (e.Fill != null && e.Height > 200)
                        {
                            e.Fill       = b;
                            t.Text       = l3.Content.ToString();
                            t.Visibility = System.Windows.Visibility.Visible;
                            e.Height     = 240;
                            e.Width      = 240;
                        }
                        else if (e.Fill != null && e.Height > 100)
                        {
                            e.Visibility = System.Windows.Visibility.Hidden;
                            t.Visibility = System.Windows.Visibility.Hidden;
                        }
                    }
                }
            }


            // store node's name in Textblock
            TextBlock txt = new TextBlock();

            txt.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
            txt.VerticalAlignment   = System.Windows.VerticalAlignment.Center;
            txt.FontSize            = 20;
            txt.Foreground          = (Brush)bc.ConvertFrom(textColor);
            txt.FontWeight          = System.Windows.FontWeights.Bold;
            txt.TextWrapping        = System.Windows.TextWrapping.Wrap;
            txt.TextTrimming        = TextTrimming.CharacterEllipsis;
            txt.Margin     = new Thickness(15, 12, 15, 10);
            txt.Text       = name;
            txt.Visibility = System.Windows.Visibility.Hidden;

            // Assign values to Labels for storing node's parent ID,
            //node's state, node's name, node's type,node's subject/discipline, and the node's fill color for the ellipse.
            Label lbl = new Label();

            lbl.Content    = nodeID;
            lbl.Visibility = System.Windows.Visibility.Hidden;
            Label lbl1 = new Label();

            lbl1.Content    = state;
            lbl1.Visibility = System.Windows.Visibility.Hidden;
            Label lbl2 = new Label();

            lbl2.Content    = name;
            lbl2.Visibility = System.Windows.Visibility.Hidden;
            Label lbl3 = new Label();

            lbl3.Content    = type;
            lbl3.Visibility = System.Windows.Visibility.Hidden;
            Label lbl4 = new Label();

            lbl4.Content    = subject;
            lbl4.Visibility = System.Windows.Visibility.Hidden;
            Label lbl5 = new Label();

            lbl5.Content    = color;
            lbl5.Visibility = System.Windows.Visibility.Hidden;

            //Add the children to the node grid. Each node grid consists of ellipse to show content, Textblock to store textual content, Labels for storing node's parent ID,
            //node's state, node's name, node's type,node's subject/discipline, and the node's fill color for the ellipse.
            Grid grid = new Grid();

            grid.Height = NodeProp[0, 2];
            grid.Width  = NodeProp[0, 2];
            grid.Children.Add(ellipse);
            grid.Children.Add(txt);
            grid.Children.Add(lbl);
            grid.Children.Add(lbl1);
            grid.Children.Add(lbl2);
            grid.Children.Add(lbl3);
            grid.Children.Add(lbl4);
            grid.Children.Add(lbl5);

            grid.MouseLeftButtonDown += new MouseButtonEventHandler(MainWindow.node_leftClick);

            //if this node has a video or image content, get its path and play/display it
            if (imgLink != "")
            {
                MainWindow.mp.Open(new Uri(@imgLink, UriKind.Relative));
                VideoDrawing vDrawing = new VideoDrawing();
                vDrawing.Rect   = new Rect(0, 0, 100, 100);
                vDrawing.Player = MainWindow.mp;
                DrawingBrush db = new DrawingBrush(vDrawing);
                ellipse.Fill = db;
                MainWindow.mp.Play();
            }
            //if this node does not have a video or image content, display its text information
            else
            {
                txt.Visibility = System.Windows.Visibility.Visible;
                txt.Text       = content;
                txt.FontSize   = 13;
                BrushConverter BC = new BrushConverter();
                Brush          b  = (Brush)BC.ConvertFrom(color);
                ellipse.Fill = b;
            }


            PaintCanvas.Children.Add(grid);


            //this code animates the node and makes it get larger gradually when selected
            DoubleAnimation da = new DoubleAnimation(1.1, new Duration(TimeSpan.FromSeconds(2)));

            ScaleTransform sc = new ScaleTransform();
            TransformGroup tg = new TransformGroup();

            tg.Children.Add(sc);        //add scaleTransform

            grid.RenderTransform       = tg;
            grid.RenderTransformOrigin = new Point(0, 0);
            sc.BeginAnimation(ScaleTransform.ScaleXProperty, da);
            sc.BeginAnimation(ScaleTransform.ScaleYProperty, da);

            Canvas.SetLeft(grid, NodeProp[0, 1] + left);
            Canvas.SetTop(grid, NodeProp[0, 0] + top);

            // this loop deals with displaying all the related nodes of this particular node
            for (int i = 0; i < relNodes.Count; i++)
            {
                ellipse                 = new Ellipse();
                ellipse.Height          = NodeProp[i + 1, 2];
                ellipse.Width           = NodeProp[i + 1, 2];
                ellipse.StrokeThickness = 1.5;
                bc           = new BrushConverter();
                brush        = (Brush)bc.ConvertFrom(relNodes.ElementAt(i).color);
                ellipse.Fill = brush;

                txt = new TextBlock();
                txt.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
                txt.VerticalAlignment   = System.Windows.VerticalAlignment.Center;
                txt.FontSize            = 16;
                txt.Foreground          = (Brush)bc.ConvertFrom(textColor);
                txt.FontWeight          = System.Windows.FontWeights.Bold;
                txt.TextWrapping        = System.Windows.TextWrapping.Wrap;
                txt.TextTrimming        = TextTrimming.CharacterEllipsis;
                txt.Margin = new Thickness(15, 12, 15, 10);
                txt.Text   = name;

                lbl             = new Label();
                lbl.Content     = relNodes.ElementAt(i).nodeID;
                lbl.Visibility  = System.Windows.Visibility.Hidden;
                lbl1            = new Label();
                lbl1.Content    = relNodes.ElementAt(i).state;
                lbl1.Visibility = System.Windows.Visibility.Hidden;
                lbl2            = new Label();
                lbl2.Content    = relNodes.ElementAt(i).name;
                lbl2.Visibility = System.Windows.Visibility.Hidden;
                lbl3            = new Label();
                lbl3.Content    = relNodes.ElementAt(i).type;
                lbl3.Visibility = System.Windows.Visibility.Hidden;
                lbl4            = new Label();
                lbl4.Content    = subject;
                lbl4.Visibility = System.Windows.Visibility.Hidden;
                lbl5            = new Label();
                lbl5.Content    = color;
                lbl5.Visibility = System.Windows.Visibility.Hidden;
                txt.Text        = relNodes.ElementAt(i).name;


                grid        = new Grid();
                grid.Height = NodeProp[i + 1, 2];
                grid.Width  = NodeProp[i + 1, 2];
                grid.Children.Add(ellipse);
                grid.Children.Add(txt);
                grid.Children.Add(lbl);
                grid.Children.Add(lbl1);
                grid.Children.Add(lbl2);
                grid.Children.Add(lbl3);
                grid.Children.Add(lbl4);
                grid.Children.Add(lbl5);
                PaintCanvas.Children.Add(grid);
                Canvas.SetLeft(grid, 0);
                Canvas.SetTop(grid, 0);

                // this code moves the related nodes from the top left corner of the screen onto the selected node
                DoubleAnimationUsingPath doublePathLR = new DoubleAnimationUsingPath();
                DoubleAnimationUsingPath doublePathUD = new DoubleAnimationUsingPath();
                TranslateTransform       tr           = new TranslateTransform();
                grid.RenderTransform = tr;
                PathGeometry pg       = new PathGeometry();
                PathFigure   pFigure  = new PathFigure();
                LineSegment  lSegment = new LineSegment();


                PathSegmentCollection collection = new PathSegmentCollection();
                collection.Add(lSegment);
                lSegment.Point = new Point(NodeProp[i + 1, 1] + left, NodeProp[i + 1, 0] + top);        //(200, 70);
                collection.Add(lSegment);
                pFigure.Segments = collection;
                PathFigureCollection conn = new PathFigureCollection();
                conn.Add(pFigure);
                pg.Figures = conn;

                doublePathLR.PathGeometry = pg;
                doublePathLR.Duration     = TimeSpan.FromSeconds(3);
                doublePathLR.Source       = PathAnimationSource.X;
                doublePathUD.PathGeometry = pg;
                doublePathUD.Duration     = TimeSpan.FromSeconds(3);
                doublePathUD.Source       = PathAnimationSource.Y;

                //this actually makes the node move; it activates the animation
                tr.BeginAnimation(TranslateTransform.XProperty, doublePathLR);
                tr.BeginAnimation(TranslateTransform.YProperty, doublePathUD);
            }
        }
コード例 #12
0
        private static void SetRenderTransform(FrameworkElement element, AnimationSettings settings, TransformGroup transform, bool updateTransformCenterPoint = false)
        {
            element.RenderTransform = transform;

            if (updateTransformCenterPoint)
            {
                element.RenderTransformOrigin = settings.TransformCenterPoint;
            }
        }
コード例 #13
0
        public ComposingAdorner2(UIElement adornedElement, Maniglie qualiManiglie) : base(adornedElement)
        {
            visualChildren = new VisualCollection(this);

            // --- GRUPPO
            transformGroup = adornedElement.RenderTransform as TransformGroup;
            if (transformGroup == null)
            {
                transformGroup = new TransformGroup();
            }

            // --- ROTAZIONE
            if (qualiManiglie == Maniglie.All || (qualiManiglie & Maniglie.Rotate) == Maniglie.Rotate)
            {
                rotateHandle        = new Thumb();
                rotateHandle.Cursor = Cursors.Hand;
                rotateHandle.Width  = HANDLESIZE;
                rotateHandle.Height = HANDLESIZE;

                rotateHandle.Background     = Brushes.Blue;
                rotateHandle.DragStarted   += rotateHandle_DragStarted;
                rotateHandle.DragDelta     += rotateHandle_DragDelta;
                rotateHandle.DragCompleted += rotateHandle_DragCompleted;

                //
                rotateTfx = initRotateBinding();
                transformGroup.Children.Add(rotateTfx);
            }

            // --- FLIP SPECCHIO
            if (qualiManiglie == Maniglie.All || (qualiManiglie & Maniglie.Flip) == Maniglie.Flip)
            {
                flipHandle                   = new Thumb();
                flipHandle.Cursor            = Cursors.Hand;
                flipHandle.Width             = 20;
                flipHandle.Height            = 20;
                flipHandle.MinWidth          = 20;
                flipHandle.MinHeight         = 20;
                flipHandle.Background        = Brushes.Orange;
                flipHandle.PreviewMouseDown += new MouseButtonEventHandler(flipHandle_MouseDown);
            }

            // --- MOVE SPOSTA TRASLA
            if (qualiManiglie == Maniglie.All || (qualiManiglie & Maniglie.Move) == Maniglie.Move)
            {
                moveHandle            = new Thumb();
                moveHandle.Cursor     = Cursors.SizeAll;
                moveHandle.Width      = double.NaN;             // grande quanto tutta la foto
                moveHandle.Height     = double.NaN;             // grande quanto tutta la foto
                moveHandle.Background = Brushes.Transparent;
                moveHandle.Opacity    = 0;

                moveHandle.DragDelta            += new DragDeltaEventHandler(moveHandle_DragDelta);
                moveHandle.DragStarted          += new DragStartedEventHandler(moveHandle_DragStarted);
                moveHandle.DragCompleted        += new DragCompletedEventHandler(moveHandle_DragCompleted);
                moveHandle.MouseRightButtonDown += new MouseButtonEventHandler(moveHandle_PreviewMouseRightButtonDown);
                moveHandle.PreviewMouseWheel    += moveHandle_PreviewMouseWheel;

                //
                translateTfx = initTransformBinding();
                transformGroup.Children.Add(translateTfx);
            }

            // --- SCALE ZOOM
            if (qualiManiglie == Maniglie.All || (qualiManiglie & Maniglie.Scale) == Maniglie.Scale)
            {
                scaleHandle            = new Thumb();
                scaleHandle.Cursor     = Cursors.SizeNS;
                scaleHandle.Width      = 20;
                scaleHandle.Height     = 20;
                scaleHandle.MinWidth   = 20;
                scaleHandle.MinHeight  = 20;
                scaleHandle.Background = Brushes.Green;

                scaleHandle.DragStarted   += scaleHandle_DragStarted;
                scaleHandle.DragDelta     += scaleHandle_DragDelta;
                scaleHandle.DragCompleted += scaleHandle_DragCompleted;

                //
                scaleFactor = 1;
                scaleTfx    = initScaleBinding();
                // TODO vedremo
                // scaleRotella = new ScaleTransform();

                transformGroup.Children.Add(scaleTfx);
            }


            // ---
            outline = new Path();

            outline.Stroke          = Brushes.Blue;
            outline.StrokeThickness = 1;

            visualChildren.Add(outline);

            if (rotateHandle != null)
            {
                visualChildren.Add(rotateHandle);
            }
            if (moveHandle != null)
            {
                visualChildren.Add(moveHandle);
            }
            if (scaleHandle != null)
            {
                visualChildren.Add(scaleHandle);
            }
            if (flipHandle != null)
            {
                visualChildren.Add(flipHandle);
            }

            adornedElement.RenderTransform = transformGroup;
        }
コード例 #14
0
        // Process the models.
        private void ProcessModels(bool invertTextures, bool zIsUp)
        {
            // Make the dictionary of materials.
            foreach (ObjMaterial material in AllMaterials)
            {
                // Make the material's MaterialGroup.
                material.MatGroup = new MaterialGroup();

                // Transparency. (Not used.)
                byte alpha = (byte)(material.Alpha * 255);

                // Diffuse.
                byte            diffR     = (byte)(material.Kd.X * 255);
                byte            diffG     = (byte)(material.Kd.Y * 255);
                byte            diffB     = (byte)(material.Kd.Z * 255);
                Color           diffColor = Color.FromArgb(255, diffR, diffG, diffB);
                SolidColorBrush diffBrush = new SolidColorBrush(diffColor);
                DiffuseMaterial diffMat   = new DiffuseMaterial(diffBrush);
                material.MatGroup.Children.Add(diffMat);

                // If it has a file, use it.
                if (material.Filename != null)
                {
                    // Use the file.
                    string     filename = material.Filename;
                    ImageBrush imgBrush = new ImageBrush();
                    imgBrush.ViewportUnits = BrushMappingMode.Absolute;
                    imgBrush.TileMode      = TileMode.Tile;

                    // Invert the texture if necessary.
                    if (invertTextures)
                    {
                        TransformGroup trans = new TransformGroup();
                        trans.Children.Add(new ScaleTransform(1, -1));
                        trans.Children.Add(new TranslateTransform(0, 1));
                        imgBrush.Transform = trans;
                    }

                    imgBrush.ImageSource = new BitmapImage(new Uri(filename, UriKind.Relative));
                    DiffuseMaterial imgMat = new DiffuseMaterial(imgBrush);
                    material.MatGroup.Children.Add(imgMat);
                }

                // Specular.
                byte             specR     = (byte)(material.Ks.X * 255);
                byte             specG     = (byte)(material.Ks.Y * 255);
                byte             specB     = (byte)(material.Ks.Z * 255);
                Color            specColor = Color.FromArgb(255, specR, specG, specB);
                SolidColorBrush  specBrush = new SolidColorBrush(specColor);
                SpecularMaterial specMat   = new SpecularMaterial(specBrush, material.Ns);
                material.MatGroup.Children.Add(specMat);

                // We ignore Ka and Tr.

                // Add it to the materials dictionary.
                MtlMaterials.Add(material.Name, material);
            }

            // Convert the object models into meshes.
            foreach (ObjModel model in AllObjectModels)
            {
                // Make the mesh.
                MeshGeometry3D mesh = new MeshGeometry3D();
                Meshes.Add(mesh);
                MeshNames.Add(model.Name);
                MaterialNames.Add(model.MaterialName);

                // Make a new list of smoothing groups.
                Dictionary <int, Dictionary <Point3D, int> > smoothingGroups =
                    new Dictionary <int, Dictionary <Point3D, int> >();

                // Entry 0 is null (no smoothing).
                smoothingGroups.Add(0, null);

                // Make the faces.
                foreach (ObjFace face in model.Faces)
                {
                    // Make the face's vertices.
                    int       numPoints = face.Vertices.Count;
                    Point3D[] points    = new Point3D[numPoints];
                    for (int i = 0; i < numPoints; i++)
                    {
                        points[i] = AllVertices[face.Vertices[i] - 1];
                    }

                    // Get texture coordinates if present.
                    Point[] textureCoords = null;
                    if (face.TextureCoords.Count > 0)
                    {
                        textureCoords = new Point[numPoints];
                        for (int i = 0; i < numPoints; i++)
                        {
                            textureCoords[i] = AllTextureCoordinates[face.TextureCoords[i] - 1];
                        }
                    }

                    // Get normals if present.
                    Vector3D[] normals = null;
                    if (face.Normals.Count > 0)
                    {
                        normals = new Vector3D[numPoints];
                        for (int i = 0; i < numPoints; i++)
                        {
                            normals[i] = AllNormals[face.Normals[i] - 1];
                        }
                    }

                    // Get the point dictionary for this smoothing group.
                    // Add new groups if needed.
                    if (!smoothingGroups.ContainsKey(face.SmoothingGroup))
                    {
                        smoothingGroups.Add(face.SmoothingGroup,
                                            new Dictionary <Point3D, int>());
                    }
                    Dictionary <Point3D, int> pointDict = smoothingGroups[face.SmoothingGroup];

                    // Make the polygon.
                    mesh.AddPolygon(pointDict: pointDict,
                                    textureCoords: textureCoords, normals: normals,
                                    points: points);
                }

                // If Z is up, rotate the model.
                if (zIsUp)
                {
                    mesh.ApplyTransformation(D3.Rotate(D3.XVector(), D3.Origin, -90));
                }
            }
        }
コード例 #15
0
        void start()
        {
            for (int i = 0; i < 10; i++)
            {
                var p = new Xamarin.Forms.Shapes.Path();
                p.Aspect = Stretch.None;

                mPathList.Add(p);
                this.Children.Add(p);
                p.Data = (Geometry)mGeometryConverter.ConvertFromInvariantString("M 0,20 L 0.8,19 L 10,19 L 10,21 L 0.8,21 Z"); // XamarinForms 版本貌似不能显示负数的内容, 故起始由9点方位的横线开始

                p.Stroke  = new SolidColorBrush(Color.White);
                p.Fill    = new SolidColorBrush(Color.White);
                p.Opacity = mMinOpacity;

                var tg = new TransformGroup();
                // TransformGroup 需要进行 2个步骤
                // 1 向上位移 50 ==> Y = -50;
                // 2 旋转一定角度, 让 12 个 Path 组成一个圆 ==> Angle = i * 30;

                var tt = new TranslateTransform();
                // tt.Y = -13; // WPF
                tt.X = 2; // 可以调整的范围 0 ~ 5
                tg.Children.Add(tt);

                var rt = new RotateTransform();
                rt.Angle   = i * 36; // 360 / 10 = 36
                rt.CenterX = 20;     // XamarinForms 版本貌似不能显示负数的内容, 故起始由9点方位的横线开始, 所以旋转以 20, 20 为中心
                rt.CenterY = 20;     // XamarinForms 版本貌似不能显示负数的内容, 故起始由9点方位的横线开始, 所以旋转以 20, 20 为中心
                tg.Children.Add(rt);

                var st = new ScaleTransform();
                mSTList.Add(st); // 程序员可以调整缩放
                st.ScaleX = 1;
                st.ScaleY = 1;
                tg.Children.Add(st);

                p.RenderTransform = tg;

                //var ani = new DoubleAnimation();
                //ani.From = mMaxOpacity;
                //ani.To = mMinOpacity;
                //ani.Duration = new Duration(TimeSpan.FromSeconds(1));

                //// 为了实现依次闪烁, 错开每个动画的开始时间
                //ani.BeginTime = TimeSpan.FromMilliseconds(i * 1000 / 12);
                //ani.RepeatBehavior = System.Windows.Media.Animation.RepeatBehavior.Forever;

                //p.BeginAnimation(System.Windows.Shapes.Path.OpacityProperty, ani);

                Animation mStoryboard = new Animation();

                // double total = 6000d;
                double total = 1000d;

                double k1 = i * 100d / total;

                // 等待动画开始执行
                if (i > 0)
                {
                    Animation s1 = new Animation
                                   (
                        callback: v => p.Opacity = v,
                        start: mMinOpacity,
                        end: mMinOpacity,
                        easing: Easing.Linear,
                        finished: null
                                   );

                    mStoryboard.Add
                    (
                        beginAt: 0,
                        finishAt: k1,
                        animation: s1
                    );
                }

                // 动画开始执行
                Animation s2 = new Animation
                               (
                    callback: v => p.Opacity = v,
                    start: mMaxOpacity,
                    end: mMinOpacity,
                    easing: Easing.Linear,
                    finished: null
                               );

                mStoryboard.Add
                (
                    beginAt: k1,
                    finishAt: 1,
                    animation: s2
                );

                mStoryboard.Commit
                (
                    owner: p,
                    name: AnimationName,
                    rate: 16,
                    length: uint.Parse(total.ToString()),
                    easing: Easing.Linear,
                    finished: null,
                    repeat: () => { return(true); }
                );

                mAnimationList.Add(mStoryboard);
            }
        }
コード例 #16
0
        protected override void UpdateData()
        {
            var geometry = (RectangleGeometry)Data;

            if (ParentMap != null &&
                !double.IsNaN(South) && !double.IsNaN(North) &&
                !double.IsNaN(West) && !double.IsNaN(East) &&
                South < North && West < East)
            {
                // Create a scaled RectangleGeometry due to inaccurate hit testing in WPF.
                // See http://stackoverflow.com/a/19335624/1136211

                const double scale = 1e6;
                var p1 = ParentMap.MapTransform.Transform(new Location(South, West));
                var p2 = ParentMap.MapTransform.Transform(new Location(North, East));
                geometry.Rect = new Rect(p1.X * scale, p1.Y * scale, (p2.X - p1.X) * scale, (p2.Y - p1.Y) * scale);

                var scaleTransform = new ScaleTransform // revert scaling
                {
                    ScaleX = 1d / scale,
                    ScaleY = 1d / scale
                };
                scaleTransform.Freeze();

                var transform = new TransformGroup();
                transform.Children.Add(scaleTransform);
                transform.Children.Add(ParentMap.ViewportTransform);
                RenderTransform = transform;
            }
            else
            {
                geometry.ClearValue(RectangleGeometry.RectProperty);
                ClearValue(RenderTransformProperty);
            }
        }
コード例 #17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ElementScreenShotInfo"/> class.
        /// </summary>
        /// <param name="targetElement">The target element.</param>
        public ElementScreenShotInfo(FrameworkElement targetElement)
        {
            FrameworkElement rootVisual = Window.Current.Content as FrameworkElement;

            this.Popup = new Popup();
            Canvas popupChild = new Canvas()
            {
                Width  = rootVisual.ActualWidth,
                Height = rootVisual.ActualHeight
            };

#if WINDOWS_PHONE
            PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
            if (frame != null)
            {
                PageOrientation pageOrientation = frame.Orientation;
                double          width           = rootVisual.ActualWidth;
                double          height          = rootVisual.ActualHeight;
                double          rotateAngle     = 0;
                double          translateX      = 0;
                double          translateY      = 0;
                switch (pageOrientation)
                {
                case PageOrientation.LandscapeLeft:
                    rotateAngle = 90;
                    translateX  = rootVisual.ActualWidth;
                    height      = rootVisual.ActualWidth;
                    width       = rootVisual.ActualHeight;
                    break;

                case PageOrientation.LandscapeRight:
                    rotateAngle = 270;
                    translateY  = rootVisual.ActualHeight;
                    height      = rootVisual.ActualWidth;
                    width       = rootVisual.ActualHeight;
                    break;

                case PageOrientation.PortraitDown:
                    rotateAngle = 180;
                    break;

                default:
                    break;
                }

                popupChild.Width  = width;
                popupChild.Height = height;
                TransformGroup transformGroup = new TransformGroup();

                RotateTransform rotateTransform = new RotateTransform();
                rotateTransform.Angle = rotateAngle;
                transformGroup.Children.Add(rotateTransform);

                TranslateTransform translateTransform = new TranslateTransform();
                translateTransform.X = translateX;
                translateTransform.Y = translateY;
                transformGroup.Children.Add(translateTransform);
                popupChild.RenderTransform = transformGroup;
            }
#endif
            this.ScreenShotContainer.Width  = targetElement.ActualWidth;
            this.ScreenShotContainer.Height = targetElement.ActualHeight;

            GeneralTransform transfrom = targetElement.TransformToVisual(rootVisual);
            this.OriginalLocation = transfrom.TransformPoint(new Point(0, 0));
            popupChild.Children.Add(this.ScreenShotContainer);
            Canvas.SetLeft(this.ScreenShotContainer, this.OriginalLocation.X);
            Canvas.SetTop(this.ScreenShotContainer, this.OriginalLocation.Y);
            this.Popup.Child      = popupChild;
            this.OriginalOpacity  = targetElement.Opacity;
            targetElement.Opacity = 0;
        }
コード例 #18
0
ファイル: MapFlow.cs プロジェクト: wangliangacc/WpfMap
        /// <summary>
        /// 将点加入到动画故事版
        /// </summary>
        /// <param name="runPoint">运动的点</param>
        /// <param name="toEll">达到城市的圆</param>
        /// <param name="sb">故事版</param>
        /// <param name="particlePath">运动轨迹</param>
        /// <param name="l">运动轨迹的直线距离</param>
        /// <param name="from">来自</param>
        /// <param name="toItem">去</param>
        private void AddPointToStoryboard(Grid runPoint, Ellipse toEll, Storyboard sb, Path particlePath, double l, ProvincialCapital from, MapToItem toItem)
        {
            double pointTime    = l / m_Speed;   //点运动所需的时间
            double particleTime = pointTime / 2; //轨迹呈现所需时间(跑的比点快两倍)
            //生成为控件注册名称的guid
            string name = Guid.NewGuid().ToString().Replace("-", "");

            #region 运动的点
            TransformGroup  tfg = new TransformGroup();
            MatrixTransform mtf = new MatrixTransform();
            tfg.Children.Add(mtf);
            TranslateTransform ttf = new TranslateTransform(-runPoint.Width / 2, -runPoint.Height / 2);//纠正最上角沿path运动到中心沿path运动
            tfg.Children.Add(ttf);
            runPoint.RenderTransform = tfg;
            _mapc.RegisterName("m" + name, mtf);

            MatrixAnimationUsingPath maup = new MatrixAnimationUsingPath();
            maup.PathGeometry          = particlePath.Data.GetFlattenedPathGeometry();
            maup.Duration              = new Duration(TimeSpan.FromSeconds(pointTime));
            maup.RepeatBehavior        = RepeatBehavior.Forever;
            maup.AutoReverse           = false;
            maup.IsOffsetCumulative    = false;
            maup.DoesRotateWithTangent = true;//沿切线旋转
            Storyboard.SetTargetName(maup, "m" + name);
            Storyboard.SetTargetProperty(maup, new PropertyPath(MatrixTransform.MatrixProperty));
            sb.Children.Add(maup);
            #endregion

            #region 达到城市的圆
            _mapc.RegisterName("ell" + name, toEll);
            //轨迹到达圆时 圆呈现
            DoubleAnimation ellda = new DoubleAnimation();
            ellda.From         = 0.2;//此处值设置0-1会有不同的呈现效果
            ellda.To           = 1;
            ellda.Duration     = new Duration(TimeSpan.FromSeconds(particleTime));
            ellda.BeginTime    = TimeSpan.FromSeconds(particleTime);//推迟动画开始时间 等轨迹连接到圆时 开始播放圆的呈现动画
            ellda.FillBehavior = FillBehavior.HoldEnd;
            Storyboard.SetTargetName(ellda, "ell" + name);
            Storyboard.SetTargetProperty(ellda, new PropertyPath(Ellipse.OpacityProperty));
            sb.Children.Add(ellda);
            //圆呈放射状
            RadialGradientBrush rgBrush = new RadialGradientBrush();
            GradientStop        gStop0  = new GradientStop(Color.FromArgb(255, 0, 0, 0), 0);
            //此为控制点 color的a值设为0 off值走0-1 透明部分向外放射 初始设为255是为了初始化效果 开始不呈放射状 等跑动的点运动到城市的圆后 color的a值才设为0开始呈现放射动画
            GradientStop gStopT = new GradientStop(Color.FromArgb(255, 0, 0, 0), 0);
            GradientStop gStop1 = new GradientStop(Color.FromArgb(255, 0, 0, 0), 1);
            rgBrush.GradientStops.Add(gStop0);
            rgBrush.GradientStops.Add(gStopT);
            rgBrush.GradientStops.Add(gStop1);
            toEll.OpacityMask = rgBrush;
            _mapc.RegisterName("e" + name, gStopT);
            //跑动的点达到城市的圆时 控制点由不透明变为透明 color的a值设为0 动画时间为0
            ColorAnimation ca = new ColorAnimation();
            ca.To           = Color.FromArgb(0, 0, 0, 0);
            ca.Duration     = new Duration(TimeSpan.FromSeconds(0));
            ca.BeginTime    = TimeSpan.FromSeconds(pointTime);
            ca.FillBehavior = FillBehavior.HoldEnd;
            Storyboard.SetTargetName(ca, "e" + name);
            Storyboard.SetTargetProperty(ca, new PropertyPath(GradientStop.ColorProperty));
            sb.Children.Add(ca);
            //点达到城市的圆时 呈现放射状动画 控制点的off值走0-1 透明部分向外放射
            DoubleAnimation eda = new DoubleAnimation();
            eda.To             = 1;
            eda.Duration       = new Duration(TimeSpan.FromSeconds(2));
            eda.RepeatBehavior = RepeatBehavior.Forever;
            eda.BeginTime      = TimeSpan.FromSeconds(particleTime);
            Storyboard.SetTargetName(eda, "e" + name);
            Storyboard.SetTargetProperty(eda, new PropertyPath(GradientStop.OffsetProperty));
            sb.Children.Add(eda);
            #endregion

            #region 运动轨迹
            //找到渐变的起点和终点
            Point startPoint = GetProvincialCapitalPoint(from);
            Point endPoint   = GetProvincialCapitalPoint(toItem.To);
            Point start      = new Point(0, 0);
            Point end        = new Point(1, 1);
            if (startPoint.X > endPoint.X)
            {
                start.X = 1;
                end.X   = 0;
            }
            if (startPoint.Y > endPoint.Y)
            {
                start.Y = 1;
                end.Y   = 0;
            }
            LinearGradientBrush lgBrush = new LinearGradientBrush();
            lgBrush.StartPoint = start;
            lgBrush.EndPoint   = end;
            GradientStop lgStop0 = new GradientStop(Color.FromArgb(255, 0, 0, 0), 0);
            GradientStop lgStop1 = new GradientStop(Color.FromArgb(0, 0, 0, 0), 0);
            lgBrush.GradientStops.Add(lgStop0);
            lgBrush.GradientStops.Add(lgStop1);
            particlePath.OpacityMask = lgBrush;
            _mapc.RegisterName("p0" + name, lgStop0);
            _mapc.RegisterName("p1" + name, lgStop1);
            //运动轨迹呈现
            DoubleAnimation pda0 = new DoubleAnimation();
            pda0.To           = 1;
            pda0.Duration     = new Duration(TimeSpan.FromSeconds(particleTime));
            pda0.FillBehavior = FillBehavior.HoldEnd;
            Storyboard.SetTargetName(pda0, "p0" + name);
            Storyboard.SetTargetProperty(pda0, new PropertyPath(GradientStop.OffsetProperty));
            sb.Children.Add(pda0);
            DoubleAnimation pda1 = new DoubleAnimation();
            //pda1.From = 0.5; //此处解开注释 值设为0-1 会有不同的轨迹呈现效果
            pda1.To           = 1;
            pda1.Duration     = new Duration(TimeSpan.FromSeconds(particleTime));
            pda1.FillBehavior = FillBehavior.HoldEnd;
            Storyboard.SetTargetName(pda1, "p1" + name);
            Storyboard.SetTargetProperty(pda1, new PropertyPath(GradientStop.OffsetProperty));
            sb.Children.Add(pda1);
            #endregion
        }
コード例 #19
0
        //cube的压缩动画
        public void CompressionOfCube()
        {
            //这个标志指示着cube复原时候到达某一帧数后做什么事情
            RepeatFlag = false;

            if (CubeCompressionCount >= 90)
            {
                return;
            }

            //在代码中初始化cube的transform参数
            Point LeftBottomPoint  = new Point(0.5, 1);
            Point RightBottomPoint = new Point(0, 1);

            UcNowCubeCom.leftbottom.RenderTransformOrigin  = LeftBottomPoint;
            UcNowCubeCom.rightbottom.RenderTransformOrigin = RightBottomPoint;

            //配置左侧的方块变形
            SkewTransform LeftSkew = new SkewTransform();

            LeftSkew.AngleY = 30;
            TranslateTransform lefttranslat = new TranslateTransform();

            lefttranslat.Y = 25.1147;

            //配置右侧的方块变形
            SkewTransform RightSkew = new SkewTransform();

            RightSkew.AngleY = -30;
            TranslateTransform righttranslat = new TranslateTransform();

            righttranslat.Y = 99.5929;

            //配置上面的菱形每帧下移的位移dy


            if (CubeCompressionCount < 90)
            {
                ScaleTransform compressionOfCube = new ScaleTransform();
                dyOfcCubeCompression    -= 0.0055;
                compressionOfCube.ScaleY = dyOfcCubeCompression;

                //配置左侧的方块变形
                var transformGroup = new TransformGroup();
                transformGroup.Children.Add(compressionOfCube);
                transformGroup.Children.Add(LeftSkew);
                transformGroup.Children.Add(lefttranslat);

                UcNowCubeCom.leftbottom.RenderTransform = transformGroup;

                //配置右侧的方块变形
                var transformGroupRight = new TransformGroup();
                transformGroupRight.Children.Add(compressionOfCube);
                transformGroupRight.Children.Add(RightSkew);
                transformGroupRight.Children.Add(righttranslat);

                UcNowCubeCom.rightbottom.RenderTransform = transformGroupRight;

                //配置上面的菱形每帧下移的位移dy,50是侧边平行四边形的高,用高减去压缩后最低点的高,然后除以90帧
                double dy = (50 - 50 * (1 - 90 * 0.0055)) / 90;

                YofCubeCompressionMoveDown = (dy * CubeCompressionCount) + 1;

                TranslateTransform moveTop = new TranslateTransform();
                moveTop.Y = YofCubeCompressionMoveDown;

                UcNowCubeCom.topface.RenderTransform = moveTop;

                CubeCompressionCount++;
            }
        }
コード例 #20
0
        /// <summary>
        /// 處理變動後的Image
        /// </summary>
        /// <param name="sourceImage">圖片來源</param>
        /// <param name="angle">旋轉角度</param>
        /// <param name="startX">裁切起始點X</param>
        /// <param name="startY">裁切起始點Y</param>
        /// <param name="width">裁切寬</param>
        /// <param name="height">裁切高</param>
        /// <param name="filePath">圖片路徑</param>
        public void DealNewImage(BitmapImage sourceImage, double angle,
                                 int startX, int startY, int width, int height,
                                 string filePath)
        {
            try
            {
                bool isEditRotate = sliderRotate.Value != defaultRotateAngle ? true : false;
                bool isEditWidth  = border.Width != rectangle.Width ? true : false;
                bool isEditHeight = border.Height != rectangle.Height ? true : false;

                bool isEditBrightness = sliderBrightness.Value != defaultBrightness ? true : false;
                bool isEditContrast   = sliderContrast.Value != defaultConstrast ? true : false;
                ContrastAdjustEffect effectBrightnessContrast = (ContrastAdjustEffect)filterBrightnessContrast.Effect;

                bool          isEditSharpen = sliderSharpen.Value != defaultSharpen ? true : false;
                SharpenEffect effectSharpen = (SharpenEffect)filterSharpen.Effect;

                bool isEditDefog    = sliderDefog.Value != defaultDefog ? true : false;
                bool isEditExposure = sliderExposure.Value != defaultExposure ? true : false;
                bool isEditGamma    = sliderGamma.Value != defaultGamma ? true : false;
                ToneMappingEffect effectExposureGamma = (ToneMappingEffect)filterExposureGamma.Effect;

                bool            isEditGrayScale = (bool)checkboxGrayScale.IsChecked ? true : false;
                GrayScaleEffect effectGrayScale = (GrayScaleEffect)filterGrayScale.Effect;

                bool isEditInvertColor = (bool)checkboxInvertColor.IsChecked ? true : false;
                InvertColorEffect effectInvertColor = (InvertColorEffect)filterInvertColor.Effect;

                if (isEditRotate || isEditWidth || isEditWidth)
                {
                    TransformGroup  transformGroup  = new TransformGroup();
                    RotateTransform rotateTransform = new RotateTransform(angle);
                    rotateTransform.CenterX = sourceImage.PixelWidth / 2.0;
                    rotateTransform.CenterY = sourceImage.PixelHeight / 2.0;
                    transformGroup.Children.Add(rotateTransform);
                    TranslateTransform translateTransform = new TranslateTransform();
                    translateTransform.X = -startX;
                    translateTransform.Y = -startY;
                    transformGroup.Children.Add(translateTransform);

                    DrawingVisual vis = new DrawingVisual();

                    RenderTargetBitmap rtb;

                    using (DrawingContext cont = vis.RenderOpen())
                    {
                        cont.PushTransform(transformGroup);
                        cont.DrawImage(sourceImage, new Rect(new Size(sourceImage.PixelWidth, sourceImage.PixelHeight)));
                        cont.Close();
                        rtb = new RenderTargetBitmap(width, height, 96d, 96d, PixelFormats.Default);
                        SaveNewImage(rtb, vis, filePath);

                        sourceImage = new CreateBitmapImage().BitmapImageOriginal(ImageInfo.Image_FullPath);
                    }
                }

                if (isEditBrightness || isEditContrast)
                {
                    DrawingVisual vis = new DrawingVisual();

                    RenderTargetBitmap rtb = new RenderTargetBitmap(sourceImage.PixelWidth, sourceImage.PixelHeight, 96d, 96d, PixelFormats.Default);;

                    using (DrawingContext cont = vis.RenderOpen())
                    {
                        cont.DrawImage(sourceImage, new Rect(new Size(sourceImage.PixelWidth, sourceImage.PixelHeight)));
                        cont.Close();

                        vis.Effect = effectBrightnessContrast;

                        SaveNewImage(rtb, vis, filePath);

                        sourceImage = new CreateBitmapImage().BitmapImageOriginal(ImageInfo.Image_FullPath);
                    }
                }

                if (isEditSharpen)
                {
                    DrawingVisual vis = new DrawingVisual();

                    RenderTargetBitmap rtb = new RenderTargetBitmap(sourceImage.PixelWidth, sourceImage.PixelHeight, 96d, 96d, PixelFormats.Default);;

                    using (DrawingContext cont = vis.RenderOpen())
                    {
                        cont.DrawImage(sourceImage, new Rect(new Size(sourceImage.PixelWidth, sourceImage.PixelHeight)));
                        cont.Close();

                        vis.Effect = effectSharpen;

                        SaveNewImage(rtb, vis, filePath);

                        sourceImage = new CreateBitmapImage().BitmapImageOriginal(ImageInfo.Image_FullPath);
                    }
                }

                if (isEditDefog || isEditExposure || isEditGamma)
                {
                    DrawingVisual vis = new DrawingVisual();

                    RenderTargetBitmap rtb = new RenderTargetBitmap(sourceImage.PixelWidth, sourceImage.PixelHeight, 96d, 96d, PixelFormats.Default);;

                    using (DrawingContext cont = vis.RenderOpen())
                    {
                        cont.DrawImage(sourceImage, new Rect(new Size(sourceImage.PixelWidth, sourceImage.PixelHeight)));
                        cont.Close();

                        vis.Effect = effectExposureGamma;

                        SaveNewImage(rtb, vis, filePath);

                        sourceImage = new CreateBitmapImage().BitmapImageOriginal(ImageInfo.Image_FullPath);
                    }
                }

                if (isEditGrayScale)
                {
                    DrawingVisual vis = new DrawingVisual();

                    RenderTargetBitmap rtb = new RenderTargetBitmap(sourceImage.PixelWidth, sourceImage.PixelHeight, 96d, 96d, PixelFormats.Default);;

                    using (DrawingContext cont = vis.RenderOpen())
                    {
                        cont.DrawImage(sourceImage, new Rect(new Size(sourceImage.PixelWidth, sourceImage.PixelHeight)));
                        cont.Close();

                        vis.Effect = effectGrayScale;

                        SaveNewImage(rtb, vis, filePath);

                        sourceImage = new CreateBitmapImage().BitmapImageOriginal(ImageInfo.Image_FullPath);
                    }
                }

                if (isEditInvertColor)
                {
                    DrawingVisual vis = new DrawingVisual();

                    RenderTargetBitmap rtb = new RenderTargetBitmap(sourceImage.PixelWidth, sourceImage.PixelHeight, 96d, 96d, PixelFormats.Default);;

                    using (DrawingContext cont = vis.RenderOpen())
                    {
                        cont.DrawImage(sourceImage, new Rect(new Size(sourceImage.PixelWidth, sourceImage.PixelHeight)));
                        cont.Close();

                        vis.Effect = effectInvertColor;

                        SaveNewImage(rtb, vis, filePath);

                        sourceImage = new CreateBitmapImage().BitmapImageOriginal(ImageInfo.Image_FullPath);
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorLog.ErrorMessageOutput(ex.ToString());
            }
        }
コード例 #21
0
        //重置cube的压缩动画,最初的版本使用,候来来被下面的CubeElasticRestore方法取代。
        public void RelaxAndResetParameterOfCubeCompression()
        {
            CubeCompressionCount = 0;

            //在代码中初始化cube的transform参数
            Point LeftBottomPoint  = new Point(0.5, 1);
            Point RightBottomPoint = new Point(0, 1);

            UcNowCubeCom.leftbottom.RenderTransformOrigin  = LeftBottomPoint;
            UcNowCubeCom.rightbottom.RenderTransformOrigin = RightBottomPoint;

            //
            ScaleTransform compressionOfCube = new ScaleTransform();

            dyOfcCubeCompression     = 1;
            compressionOfCube.ScaleY = dyOfcCubeCompression;

            //配置左侧的方块变形
            SkewTransform LeftSkew = new SkewTransform();

            LeftSkew.AngleY = 30;
            TranslateTransform lefttranslat = new TranslateTransform();

            lefttranslat.Y = 25.1147;

            //配置右侧的方块变形
            SkewTransform RightSkew = new SkewTransform();

            RightSkew.AngleY = -30;
            TranslateTransform righttranslat = new TranslateTransform();

            righttranslat.Y = 99.5929;

            //配置左侧的方块变形
            var transformGroup = new TransformGroup();

            transformGroup.Children.Add(compressionOfCube);
            transformGroup.Children.Add(LeftSkew);
            transformGroup.Children.Add(lefttranslat);

            UcNowCubeCom.leftbottom.RenderTransform = transformGroup;

            //配置右侧的方块变形
            var transformGroupRight = new TransformGroup();

            transformGroupRight.Children.Add(compressionOfCube);
            transformGroupRight.Children.Add(RightSkew);
            transformGroupRight.Children.Add(righttranslat);

            UcNowCubeCom.rightbottom.RenderTransform = transformGroupRight;

            //配置上面的菱形每帧下移的位移dy
            double dy = 0;

            YofCubeCompressionMoveDown = dy * CubeCompressionCount;

            TranslateTransform moveTop = new TranslateTransform();

            moveTop.Y = YofCubeCompressionMoveDown;

            UcNowCubeCom.topface.RenderTransform = moveTop;
        }
コード例 #22
0
ファイル: MyAniTada.cs プロジェクト: oldsyang/MyWPFUI
        public override MyAnimateBase Animate()
        {
            IsAnimateCompleted            = false;
            Element.Visibility            = Visibility.Visible;
            Element.RenderTransformOrigin = new Point(0.5, 0.5);

            RotateTransform translation      = new RotateTransform();
            ScaleTransform  translationScale = new ScaleTransform(1, 1);

            string translationName      = "";
            string translationScaleName = "";

            Storyboard story = new Storyboard();
            DoubleAnimationUsingKeyFrames dau = new DoubleAnimationUsingKeyFrames();

            #region 基本工作,确定类型和name
            //是否存在TranslateTransform
            //动画要的类型是否存在
            //动画要的类型的name是否存在,不存在就注册,结束后取消注册,删除动画
            var ex = Element.RenderTransform;
            if (ex == null || (ex as System.Windows.Media.MatrixTransform) != null)
            {
                var tg = new TransformGroup();
                translation     = new RotateTransform();
                translationName = "ayTranslation" + translation.GetHashCode();
                Win.RegisterName(translationName, translation);
                tg.Children.Add(translation);

                translationScaleName = "ayTranslation" + translationScale.GetHashCode();
                Win.RegisterName(translationScaleName, translationScale);
                tg.Children.Add(translationScale);

                Element.RenderTransform = tg;
            }
            else
            {
                var tg = ex as TransformGroup;
                foreach (var item in tg.Children)
                {
                    translation = item as RotateTransform;
                    if (translation != null)
                    {
                        break;
                    }
                }
                foreach (var item in tg.Children)
                {
                    translationScale = item as ScaleTransform;
                    if (translationScale != null)
                    {
                        break;
                    }
                }

                if (translation != null)
                {
                    //当前Y值
                    var tex = translation.GetValue(FrameworkElement.NameProperty);
                    if (tex != null && tex.ToString() != "")
                    {
                        translationName = tex.ToString();
                    }
                    else
                    {
                        translationName = "ayTranslation" + translation.GetHashCode();
                        Win.RegisterName(translationName, translation);
                    }
                }
                else
                {
                    translation     = new RotateTransform();
                    translationName = "ayTranslation" + translation.GetHashCode();
                    Win.RegisterName(translationName, translation);
                    tg.Children.Add(translation);
                    Element.RenderTransform = tg;
                }

                if (translationScale != null)
                {
                    var tex = translationScale.GetValue(FrameworkElement.NameProperty);
                    if (tex != null && tex.ToString() != "")
                    {
                        translationScaleName = tex.ToString();
                    }
                    else
                    {
                        translationScaleName = "ayTranslation" + translationScale.GetHashCode();
                        Win.RegisterName(translationScaleName, translationScale);
                    }
                }
                else
                {
                    translationScale     = new ScaleTransform(1, 1);
                    translationScaleName = "ayTranslation" + translationScale.GetHashCode();
                    Win.RegisterName(translationScaleName, translationScale);
                    tg.Children.Add(translationScale);
                    Element.RenderTransform = tg;
                }
            }
            #endregion

            translation.CenterX = 0.5;
            translation.CenterY = 0;
            double angle = translation.Angle;
            var    k2    = new EasingDoubleKeyFrame(angle - 3, TimeSpan.FromMilliseconds(AniTime(0.1)));
            var    k2_1  = new EasingDoubleKeyFrame(angle - 3, TimeSpan.FromMilliseconds(AniTime(0.2)));
            var    k2_2  = new EasingDoubleKeyFrame(angle + 3, TimeSpan.FromMilliseconds(AniTime(0.3)));
            var    k2_3  = new EasingDoubleKeyFrame(angle + 3, TimeSpan.FromMilliseconds(AniTime(0.5)));
            var    k2_4  = new EasingDoubleKeyFrame(angle + 3, TimeSpan.FromMilliseconds(AniTime(0.7)));
            var    k2_5  = new EasingDoubleKeyFrame(angle + 3, TimeSpan.FromMilliseconds(AniTime(0.9)));
            var    k2_6  = new EasingDoubleKeyFrame(angle - 3, TimeSpan.FromMilliseconds(AniTime(0.4)));
            var    k2_7  = new EasingDoubleKeyFrame(angle - 3, TimeSpan.FromMilliseconds(AniTime(0.6)));
            var    k2_8  = new EasingDoubleKeyFrame(angle - 3, TimeSpan.FromMilliseconds(AniTime(0.8)));
            var    k2_9  = new EasingDoubleKeyFrame(angle, TimeSpan.FromMilliseconds(AnimateSpeed));

            Storyboard.SetTargetName(dau, translationName);
            Storyboard.SetTargetProperty(dau, new PropertyPath(RotateTransform.AngleProperty));

            var storyboardName = "aystory" + story.GetHashCode();
            Win.Resources.Add(storyboardName, story);

            dau.KeyFrames.Add(k2);
            dau.KeyFrames.Add(k2_1);
            dau.KeyFrames.Add(k2_2);
            dau.KeyFrames.Add(k2_3);
            dau.KeyFrames.Add(k2_4);
            dau.KeyFrames.Add(k2_5);
            dau.KeyFrames.Add(k2_6);
            dau.KeyFrames.Add(k2_7);
            dau.KeyFrames.Add(k2_8);
            dau.KeyFrames.Add(k2_9);

            story.Children.Add(dau);


            DoubleAnimationUsingKeyFrames dauScaleX = new DoubleAnimationUsingKeyFrames();
            DoubleAnimationUsingKeyFrames dauScaleY = new DoubleAnimationUsingKeyFrames();
            double scaleX = translationScale.ScaleX;
            double scaleY = translationScale.ScaleY;
            double s1     = scaleX + tadaScale;
            double s2     = scaleX - tadaScale;

            double s3 = scaleY + tadaScale;
            double s4 = scaleY - tadaScale;

            var k3   = new EasingDoubleKeyFrame(s2, TimeSpan.FromMilliseconds(AniTime(0.1)));
            var k3_1 = new EasingDoubleKeyFrame(s2, TimeSpan.FromMilliseconds(AniTime(0.2)));
            var k3_2 = new EasingDoubleKeyFrame(s1, TimeSpan.FromMilliseconds(AniTime(0.3)));
            var k3_3 = new EasingDoubleKeyFrame(s1, TimeSpan.FromMilliseconds(AniTime(0.5)));
            var k3_4 = new EasingDoubleKeyFrame(s1, TimeSpan.FromMilliseconds(AniTime(0.7)));
            var k3_5 = new EasingDoubleKeyFrame(s1, TimeSpan.FromMilliseconds(AniTime(0.9)));
            var k3_6 = new EasingDoubleKeyFrame(s1, TimeSpan.FromMilliseconds(AniTime(0.4)));
            var k3_7 = new EasingDoubleKeyFrame(s1, TimeSpan.FromMilliseconds(AniTime(0.6)));
            var k3_8 = new EasingDoubleKeyFrame(s1, TimeSpan.FromMilliseconds(AniTime(0.8)));
            var k3_9 = new EasingDoubleKeyFrame(scaleX, TimeSpan.FromMilliseconds(AnimateSpeed));


            var k4   = new EasingDoubleKeyFrame(s4, TimeSpan.FromMilliseconds(AniTime(0.1)));
            var k4_1 = new EasingDoubleKeyFrame(s4, TimeSpan.FromMilliseconds(AniTime(0.2)));
            var k4_2 = new EasingDoubleKeyFrame(s3, TimeSpan.FromMilliseconds(AniTime(0.3)));
            var k4_3 = new EasingDoubleKeyFrame(s3, TimeSpan.FromMilliseconds(AniTime(0.5)));
            var k4_4 = new EasingDoubleKeyFrame(s3, TimeSpan.FromMilliseconds(AniTime(0.7)));
            var k4_5 = new EasingDoubleKeyFrame(s3, TimeSpan.FromMilliseconds(AniTime(0.9)));
            var k4_6 = new EasingDoubleKeyFrame(s3, TimeSpan.FromMilliseconds(AniTime(0.4)));
            var k4_7 = new EasingDoubleKeyFrame(s3, TimeSpan.FromMilliseconds(AniTime(0.6)));
            var k4_8 = new EasingDoubleKeyFrame(s3, TimeSpan.FromMilliseconds(AniTime(0.8)));
            var k4_9 = new EasingDoubleKeyFrame(scaleY, TimeSpan.FromMilliseconds(AnimateSpeed));


            Storyboard.SetTargetName(dauScaleX, translationScaleName);
            Storyboard.SetTargetProperty(dauScaleX, new PropertyPath(ScaleTransform.ScaleXProperty));
            Storyboard.SetTargetName(dauScaleY, translationScaleName);
            Storyboard.SetTargetProperty(dauScaleY, new PropertyPath(ScaleTransform.ScaleYProperty));

            dauScaleX.KeyFrames.Add(k3);
            dauScaleX.KeyFrames.Add(k3_1);
            dauScaleX.KeyFrames.Add(k3_2);
            dauScaleX.KeyFrames.Add(k3_3);
            dauScaleX.KeyFrames.Add(k3_4);
            dauScaleX.KeyFrames.Add(k3_5);
            dauScaleX.KeyFrames.Add(k3_6);
            dauScaleX.KeyFrames.Add(k3_7);
            dauScaleX.KeyFrames.Add(k3_8);
            dauScaleX.KeyFrames.Add(k3_9);

            story.Children.Add(dauScaleX);


            dauScaleY.KeyFrames.Add(k4);
            dauScaleY.KeyFrames.Add(k4_1);
            dauScaleY.KeyFrames.Add(k4_2);
            dauScaleY.KeyFrames.Add(k4_3);
            dauScaleY.KeyFrames.Add(k4_4);
            dauScaleY.KeyFrames.Add(k4_5);
            dauScaleY.KeyFrames.Add(k4_6);
            dauScaleY.KeyFrames.Add(k4_7);
            dauScaleY.KeyFrames.Add(k4_8);
            dauScaleY.KeyFrames.Add(k4_9);

            story.Children.Add(dauScaleY);


            story.Completed +=
                (sndr, evtArgs) =>
            {
                try
                {
                    Win.Resources.Remove(storyboardName);
                    Win.UnregisterName(translationName);
                    Win.UnregisterName(translationScaleName);
                    dau.KeyFrames.Clear();
                    dauScaleX.KeyFrames.Clear();
                    dauScaleY.KeyFrames.Clear();
                    dauScaleX = null;
                    dauScaleY = null;
                    dau       = null;
                    story     = null;

                    base.CallClientCompleted();
                }
                catch
                {
                }
            };
            story.Begin(); return(this);
        }
コード例 #23
0
        //方块弹性形变后恢复的效果。无论小人是哪种情况,只要跳起,cube都有这个效果。
        //定为15帧内完成。短动画为15帧,刚好在它之内可以完成,长动画30帧,存在重复的现象,加入了标志位避免重复
        public void CubeElasticRestore()
        {
            //这个标志指示着cube复原时候超过15帧就不进行下面的操作,因为下面的操作本来就在15帧运行OK,只不过有的动画需要30帧来演示。假如不设置这个判断,又开始cube还原了
            if (RepeatFlag)
            {
                return;
            }
            CubeCompressionCount = 0;

            //在代码中初始化cube的transform参数
            Point LeftBottomPoint  = new Point(0.5, 1);
            Point RightBottomPoint = new Point(0, 1);

            UcNowCubeCom.leftbottom.RenderTransformOrigin  = LeftBottomPoint;
            UcNowCubeCom.rightbottom.RenderTransformOrigin = RightBottomPoint;


            if (CubeRestoreCounts < 15)
            {
                //配置上面的菱形每帧弹性还原的位移dy,15帧内运行完弹性动画
                double             t       = (1d / 15) * CubeRestoreCounts++;
                TranslateTransform moveTop = new TranslateTransform();
                moveTop.Y = 25 * (1 - ElasticFucntion(t));
                UcNowCubeCom.topface.RenderTransform = moveTop;

                //配置两侧方块每帧弹性还原的百分比
                ScaleTransform compressionOfCube = new ScaleTransform();
                dyOfcCubeCompression     = (50 - 25 * (1 - ElasticFucntion(t))) / 50;
                compressionOfCube.ScaleY = dyOfcCubeCompression;

                //配置左侧的方块还原
                SkewTransform LeftSkew = new SkewTransform();
                LeftSkew.AngleY = 30;
                TranslateTransform lefttranslat = new TranslateTransform();
                lefttranslat.Y = 25.1147;

                //配置右侧的方块还原
                SkewTransform RightSkew = new SkewTransform();
                RightSkew.AngleY = -30;
                TranslateTransform righttranslat = new TranslateTransform();
                righttranslat.Y = 99.5929;

                //配置左侧的方块还原
                var transformGroup = new TransformGroup();
                transformGroup.Children.Add(compressionOfCube);
                transformGroup.Children.Add(LeftSkew);
                transformGroup.Children.Add(lefttranslat);

                UcNowCubeCom.leftbottom.RenderTransform = transformGroup;

                //配置右侧的方块还原
                var transformGroupRight = new TransformGroup();
                transformGroupRight.Children.Add(compressionOfCube);
                transformGroupRight.Children.Add(RightSkew);
                transformGroupRight.Children.Add(righttranslat);

                UcNowCubeCom.rightbottom.RenderTransform = transformGroupRight;
            }
            //还原动画的最后一帧,将CubeRestoreCounts重置为0。为了避免长动画时继续进入上面的循环,加了一个标志位,RepeatFlag
            if (CubeRestoreCounts == 14)
            {
                CubeRestoreCounts = 0;
                RepeatFlag        = true;
            }
        }
コード例 #24
0
        private static CompositeTransform GetAttachedCompositeTransform(UIElement element)
        {
            // We need to use an index to keep track of our CompositeTransform as animation engine
            // recreates new transform objects when animating properties

            // Already attached?
            var compositeTransformIndex = AnimationTools.GetAnimationCompositeTransformIndex(element);

            if (compositeTransformIndex > -2)
            {
                if (compositeTransformIndex == -1 && element.RenderTransform is CompositeTransform)
                {
                    return((CompositeTransform)element.RenderTransform);
                }

                var group = element.RenderTransform as TransformGroup;

                if (group?.Children.Count > compositeTransformIndex && group.Children[compositeTransformIndex] is CompositeTransform)
                {
                    return((CompositeTransform)group.Children[compositeTransformIndex]);
                }
            }

            // Let's create a new CompositeTransform
            var result = new CompositeTransform();

            var currentTransform = element.RenderTransform;

            if (currentTransform != null)
            {
                // We found a RenderTransform

                // Is it a TransformGroup?
                var currentTransformGroup = currentTransform as TransformGroup;

                if (currentTransformGroup != null)
                {
                    currentTransformGroup.Children.Add(result);

                    AnimationTools.SetAnimationCompositeTransformIndex(element, currentTransformGroup.Children.Count - 1);
                }
                else
                {
                    // Let's create our own TransformGroup
                    var group = new TransformGroup();
                    group.Children.Add(currentTransform);
                    group.Children.Add(result);
                    element.RenderTransform = group;

                    AnimationTools.SetAnimationCompositeTransformIndex(element, 1);
                }
            }
            else
            {
                element.RenderTransform = result;

                AnimationTools.SetAnimationCompositeTransformIndex(element, -1);
            }

            return(result);
        }
コード例 #25
0
        public override DocumentPage GetPage(int pageNumber)
        {
            // Use default paginator to handle pagination
            Visual originalPage = paginator.GetPage(pageNumber).Visual;

            ContainerVisual visual     = new ContainerVisual();
            ContainerVisual pageVisual = new ContainerVisual()
            {
                Transform = new TranslateTransform(
                    definition.ContentOrigin.X,
                    definition.ContentOrigin.Y
                    )
            };

            pageVisual.Children.Add(originalPage);
            visual.Children.Add(pageVisual);

            // Create headers and footers
            if (definition.Header != null)
            {
                visual.Children.Add(CreateHeaderFooterVisual(definition.Header, definition.HeaderRect, pageNumber));
            }
            if (definition.Footer != null)
            {
                visual.Children.Add(CreateHeaderFooterVisual(definition.Footer, definition.FooterRect, pageNumber));
            }

            // Check for repeating table headers
            if (definition.RepeatTableHeaders)
            {
                // Find table header
                // ReSharper disable NotAccessedVariable
                ContainerVisual table;
                // ReSharper enable NotAccessedVariable
                if (PageStartsWithTable(originalPage, out table) && currentHeader != null)
                {
                    // The page starts with a table and a table header was
                    // found on the previous page. Presumably this table
                    // was started on the previous page, so we'll repeat the
                    // table header.
                    Rect            headerBounds      = VisualTreeHelper.GetDescendantBounds(currentHeader);
                    ContainerVisual tableHeaderVisual = new ContainerVisual();

                    // Translate the header to be at the top of the page
                    // instead of its previous position
                    tableHeaderVisual.Transform = new TranslateTransform(
                        definition.ContentOrigin.X,
                        definition.ContentOrigin.Y - headerBounds.Top
                        );

                    // Since we've placed the repeated table header on top of the
                    // content area, we'll need to scale down the rest of the content
                    // to accomodate this. Since the table header is relatively small,
                    // this probably is barely noticeable.
                    double yScale =
                        (definition.ContentSize.Height - headerBounds.Height) / definition.ContentSize.Height;
                    TransformGroup group = new TransformGroup();
                    group.Children.Add(new ScaleTransform(1.0, yScale));
                    group.Children.Add(new TranslateTransform(
                                           definition.ContentOrigin.X,
                                           definition.ContentOrigin.Y + headerBounds.Height
                                           ));
                    pageVisual.Transform = group;

                    ContainerVisual cp = VisualTreeHelper.GetParent(currentHeader) as ContainerVisual;
                    if (cp != null)
                    {
                        cp.Children.Remove(currentHeader);
                    }
                    tableHeaderVisual.Children.Add(currentHeader);
                    visual.Children.Add(tableHeaderVisual);
                }

                // Check if there is a table on the bottom of the page.
                // If it's there, its header should be repeated
                // ReSharper disable UnusedVariable
                if (PageEndsWithTable(originalPage, out ContainerVisual newTable, out ContainerVisual newHeader))
                // ReSharper enable UnusedVariable
                {
                    // "lock" only once the header
                    if (currentHeader == null)
                    {
                        currentHeader = newHeader;
                    }
                }
                else
                {
                    // There was no table at the end of the page
                    currentHeader = null;
                }
            }
コード例 #26
0
ファイル: LevelsResourses.cs プロジェクト: Bonzatina/prog4
        public LevelsResourses()
        {
            // first screen

            // arrays of points for grounds
            Point[] oneSlice1 = new Point[] {
                new Point(0, 0),
                new Point(230, 0),
                new Point(280, 100),
                new Point(730, -80),
                new Point(1280, -80),
            };

            Point[] secondSlice1 = new Point[]
            {
                new Point(280, -100),
                new Point(320, -100),
            };

            Point[] thirdSlice1 = new Point[]
            {
                new Point(700, 120),
                new Point(860, 120),
                new Point(970, 20),
            };
            Point[][] grounds1 = new Point[][] { oneSlice1, secondSlice1, thirdSlice1 };


            // fill specialItems List
            List <SpecialItem> specialItems1 = new List <SpecialItem>();
            // get from Shapes dictionary needed shape
            Geometry plusOneLiveShape1 = GameShapes.gameShapes["plusOneLiveShape"];
            // create tranformation for it which will define it's position relative to x = 0, y = GameModel.ZeroAxios
            TransformGroup plusOneLiveShape1Transform = new TransformGroup();

            plusOneLiveShape1Transform.Children.Add(new TranslateTransform(300, -100)); // offsets from  x = 0, y = GameModel.ZeroAxios
            plusOneLiveShape1.Transform = plusOneLiveShape1Transform;
            // get final shape now we can add it to List
            plusOneLiveShape1 = plusOneLiveShape1.GetFlattenedPathGeometry();

            // go to next shape ...
            Geometry       spikesShape1         = GameShapes.gameShapes["spikesShape"];
            TransformGroup spikesShape1Tranform = new TransformGroup();

            spikesShape1Tranform.Children.Add(new TranslateTransform(180, 0));
            spikesShape1Tranform.Children.Add(new MatrixTransform(new Matrix(1, 0, 0, -1, 0, 0)));
            spikesShape1.Transform = spikesShape1Tranform;
            spikesShape1           = spikesShape1.GetFlattenedPathGeometry();

            Geometry       spikesShape_1_2          = GameShapes.gameShapes["spikesShape"];
            TransformGroup spikesShape_1_2_Tranform = new TransformGroup();

            spikesShape_1_2_Tranform.Children.Add(new TranslateTransform(730, -80));
            spikesShape_1_2.Transform = spikesShape_1_2_Tranform;
            spikesShape_1_2           = spikesShape_1_2.GetFlattenedPathGeometry();;

            Geometry       plusScoresShape1          = GameShapes.gameShapes["plusScoresShape"];
            TransformGroup plusScoresShape1Transform = new TransformGroup();

            plusScoresShape1Transform.Children.Add(new TranslateTransform(480, 40));
            plusScoresShape1.Transform = plusScoresShape1Transform;
            plusScoresShape1           = plusScoresShape1.GetFlattenedPathGeometry();

            Geometry       plusScoresShape2          = GameShapes.gameShapes["plusScoresShape"];
            TransformGroup plusScoresShape2Transform = new TransformGroup();

            plusScoresShape2Transform.Children.Add(new TranslateTransform(750, 140));
            plusScoresShape2.Transform = plusScoresShape2Transform;
            plusScoresShape2           = plusScoresShape2.GetFlattenedPathGeometry();


            Geometry       wallShape1         = GameShapes.gameShapes["wallShape"];
            TransformGroup wallShape1Tranform = new TransformGroup();

            wallShape1Tranform.Children.Add(new TranslateTransform(575, -103));
            wallShape1.Transform = wallShape1Tranform;
            wallShape1           = wallShape1.GetFlattenedPathGeometry();

            specialItems1.Add(new IncreaseHealthItem(1, Brushes.BlueViolet, new Pen(Brushes.Black, 2), plusOneLiveShape1));
            specialItems1.Add(new DecreaseHealthItem(1, Brushes.Red, new Pen(Brushes.Black, 2), spikesShape1));
            specialItems1.Add(new DecreaseHealthItem(1, Brushes.Red, new Pen(Brushes.Black, 2), spikesShape_1_2));
            specialItems1.Add(new WallItem(Brushes.DarkKhaki, new Pen(Brushes.DarkGray, 2), wallShape1));
            specialItems1.Add(new IncreasePlayerScoreItem(Brushes.Gold, new Pen(Brushes.Red, 2), plusScoresShape1));
            specialItems1.Add(new IncreasePlayerScoreItem(Brushes.Gold, new Pen(Brushes.Red, 2), plusScoresShape2));

            // fill enemies ...
            List <Enemy>   enemies1                  = new List <Enemy>();
            Geometry       smallEnemyShape1          = GameShapes.gameShapes["smallEnemyShape"];
            TransformGroup smallEnemyShape1Transform = new TransformGroup();

            smallEnemyShape1Transform.Children.Add(new TranslateTransform(450, 40));
            smallEnemyShape1.Transform = smallEnemyShape1Transform;
            smallEnemyShape1           = smallEnemyShape1.GetFlattenedPathGeometry();

            //Geometry mediumEnemyShape2 = GameShapes.gameShapes["mediumEnemyShape"];
            //TransformGroup mediumEnemyShape2Transform = new TransformGroup();
            //mediumEnemyShape2Transform.Children.Add(new TranslateTransform(650, 135));
            //mediumEnemyShape2.Transform = mediumEnemyShape2Transform;
            //mediumEnemyShape2 = mediumEnemyShape2.GetFlattenedPathGeometry();

            enemies1.Add(new SmallEnemy(smallEnemyShape1));
            //enemies1.Add(new MediumEnemy(mediumEnemyShape2));


            // exit to next game screen
            Geometry doorNextScreenShape1 = new LineGeometry(new Point(0, 0), new Point(0, -160))
                                            .GetWidenedPathGeometry(new Pen(Brushes.Black, 2));
            TransformGroup doorNextScreenShape1Transform = new TransformGroup();

            doorNextScreenShape1Transform.Children.Add(new TranslateTransform(1263, 0));
            doorNextScreenShape1.Transform = doorNextScreenShape1Transform;
            doorNextScreenShape1           = doorNextScreenShape1.GetFlattenedPathGeometry();
            DoorNextScreen doorNextScreen1 = new DoorNextScreen("screen_2", Brushes.Black, new Pen(Brushes.Black, 5), doorNextScreenShape1);

            screens.Add("screen_1", new Screen(new GroundLine(grounds1), doorNextScreen1, specialItems1, enemies1));


            // second screen
            Point[] oneSlice2 = new Point[] {
                new Point(0, 0),
                new Point(150, 0),
                new Point(330, -230),
                new Point(930, -230),
                new Point(1200, 70),
                new Point(1280, 70),
            };
            Point[] secondSlice2 = new Point[] {
                new Point(330, 100),
                new Point(500, 200),
            };
            Point[] thirdSlice2 = new Point[] {
                new Point(580, 0),
                new Point(750, 100),
            };

            Point[][] grounds2 = new Point[][] { oneSlice2, secondSlice2, thirdSlice2 };

            List <SpecialItem> specialItems2            = new List <SpecialItem>();
            Geometry           spikesShape_2_1          = GameShapes.gameShapes["spikesShape"];
            TransformGroup     spikesShape_2_1_Tranform = new TransformGroup();

            spikesShape_2_1_Tranform.Children.Add(new TranslateTransform(600, 230));
            spikesShape_2_1_Tranform.Children.Add(new MatrixTransform(new Matrix(1, 0, 0, -1, 0, 0)));
            spikesShape_2_1.Transform = spikesShape_2_1_Tranform;
            spikesShape_2_1           = spikesShape_2_1.GetFlattenedPathGeometry();;

            Geometry       plusScoresShape2_1          = GameShapes.gameShapes["plusScoresShape"];
            TransformGroup plusScoresShape2_1Transform = new TransformGroup();

            plusScoresShape2_1Transform.Children.Add(new TranslateTransform(530, -175));
            plusScoresShape2_1.Transform = plusScoresShape2_1Transform;
            plusScoresShape2_1           = plusScoresShape2_1.GetFlattenedPathGeometry();

            Geometry       plusScoresShape2_2          = GameShapes.gameShapes["plusScoresShape"];
            TransformGroup plusScoresShape2_2Transform = new TransformGroup();

            plusScoresShape2_2Transform.Children.Add(new TranslateTransform(670, -90));
            plusScoresShape2_2.Transform = plusScoresShape2_2Transform;
            plusScoresShape2_2           = plusScoresShape2_2.GetFlattenedPathGeometry();

            Geometry       plusOneLiveShape_2_1          = GameShapes.gameShapes["plusOneLiveShape"];
            TransformGroup plusOneLiveShape_2_1Transform = new TransformGroup();

            plusOneLiveShape_2_1Transform.Children.Add(new TranslateTransform(635, 232));
            plusOneLiveShape_2_1Transform.Children.Add(new MatrixTransform(new Matrix(1, 0, 0, -1, 0, 0)));
            plusOneLiveShape_2_1.Transform = plusOneLiveShape_2_1Transform;
            plusOneLiveShape_2_1           = plusOneLiveShape_2_1.GetFlattenedPathGeometry();

            specialItems2.Add(new DecreaseHealthItem(1, Brushes.Red, new Pen(Brushes.Black, 2), spikesShape_2_1));
            specialItems2.Add(new IncreasePlayerScoreItem(Brushes.Gold, new Pen(Brushes.Red, 2), plusScoresShape2_1));
            specialItems2.Add(new IncreasePlayerScoreItem(Brushes.Gold, new Pen(Brushes.Red, 2), plusScoresShape2_2));
            specialItems2.Add(new IncreaseHealthItem(1, Brushes.BlueViolet, new Pen(Brushes.Black, 2), plusOneLiveShape_2_1));

            List <Enemy> enemies2 = new List <Enemy>();

            Geometry       smallEnemyShape_2_1          = GameShapes.gameShapes["smallEnemyShape"];
            TransformGroup smallEnemyShape_2_1Transform = new TransformGroup();

            smallEnemyShape_2_1Transform.Children.Add(new TranslateTransform(680, 65));
            smallEnemyShape_2_1.Transform = smallEnemyShape_2_1Transform;
            smallEnemyShape_2_1           = smallEnemyShape_2_1.GetFlattenedPathGeometry();

            Geometry       mediumEnemyShape2_1          = GameShapes.gameShapes["mediumEnemyShape"];
            TransformGroup mediumEnemyShape2_1Transform = new TransformGroup();

            mediumEnemyShape2_1Transform.Children.Add(new TranslateTransform(440, -225));
            mediumEnemyShape2_1.Transform = mediumEnemyShape2_1Transform;
            mediumEnemyShape2_1           = mediumEnemyShape2_1.GetFlattenedPathGeometry();

            Geometry       mediumEnemyShape2_2          = GameShapes.gameShapes["mediumEnemyShape"];
            TransformGroup mediumEnemyShape2_2Transform = new TransformGroup();

            mediumEnemyShape2_2Transform.Children.Add(new TranslateTransform(800, -225));
            mediumEnemyShape2_2.Transform = mediumEnemyShape2_2Transform;
            mediumEnemyShape2_2           = mediumEnemyShape2_2.GetFlattenedPathGeometry();

            enemies2.Add(new SmallEnemy(smallEnemyShape_2_1));
            enemies2.Add(new MediumEnemy(mediumEnemyShape2_1));
            enemies2.Add(new MediumEnemy(mediumEnemyShape2_2));


            Geometry doorNextScreenShape2 = new LineGeometry(new Point(0, 0), new Point(0, -160))
                                            .GetWidenedPathGeometry(new Pen(Brushes.Black, 2));
            TransformGroup doorNextScreenShape2Transform = new TransformGroup();

            doorNextScreenShape2Transform.Children.Add(new TranslateTransform(1263, 140));
            doorNextScreenShape2.Transform = doorNextScreenShape2Transform;
            doorNextScreenShape2           = doorNextScreenShape2.GetFlattenedPathGeometry();
            DoorNextScreen doorNextScreen2 = new DoorNextScreen("screen_3", Brushes.Black, new Pen(Brushes.Black, 5), doorNextScreenShape2);

            screens.Add("screen_2", new Screen(new GroundLine(grounds2), doorNextScreen2, specialItems2, enemies2));


            // third screen
            Point[] oneSlice3 = new Point[] {
                new Point(0, 0),
                new Point(100, 0),
                new Point(200, -30),
                new Point(300, -30),
                new Point(380, -160),
                new Point(490, -140),
                new Point(750, 140),
                new Point(950, 140),
                new Point(1150, 10),
                new Point(1280, 10),
            };
            Point[] secondSlice3 = new Point[] {
                new Point(720, -200),
                new Point(880, -210),
                new Point(960, -110),
            };
            Point[] thirdSlice3 = new Point[] {
                new Point(241, 100),
                new Point(400, 100),
            };
            Point[][] grounds3 = new Point[][] { oneSlice3, secondSlice3, thirdSlice3 };

            List <SpecialItem> specialItems3            = new List <SpecialItem>();
            Geometry           spikesShape_3_1          = GameShapes.gameShapes["spikesShape"];
            TransformGroup     spikesShape_3_1_Tranform = new TransformGroup();

            spikesShape_3_1_Tranform.Children.Add(new TranslateTransform(665, 50));
            spikesShape_3_1_Tranform.Children.Add(new RotateTransform(50, 665, 50));
            spikesShape_3_1.Transform = spikesShape_3_1_Tranform;
            spikesShape_3_1           = spikesShape_3_1.GetFlattenedPathGeometry();

            Geometry       spikesShape_3_2          = GameShapes.gameShapes["spikesShape"];
            TransformGroup spikesShape_3_2_Tranform = new TransformGroup();

            spikesShape_3_2_Tranform.Children.Add(new TranslateTransform(355, -125));
            spikesShape_3_2_Tranform.Children.Add(new RotateTransform(55, 355, -125));
            spikesShape_3_2_Tranform.Children.Add(new ScaleTransform(1, -1, 355, -125));
            spikesShape_3_2.Transform = spikesShape_3_2_Tranform;
            spikesShape_3_2           = spikesShape_3_2.GetFlattenedPathGeometry();

            Geometry       wallShape3         = GameShapes.gameShapes["wallShape"];
            TransformGroup wallShape3Tranform = new TransformGroup();

            wallShape3Tranform.Children.Add(new TranslateTransform(275, -110));
            wallShape3.Transform = wallShape3Tranform;
            wallShape3           = wallShape3.GetFlattenedPathGeometry();

            Geometry       plusOneLiveShape_3_1          = GameShapes.gameShapes["plusOneLiveShape"];
            TransformGroup plusOneLiveShape_3_1Transform = new TransformGroup();

            plusOneLiveShape_3_1Transform.Children.Add(new TranslateTransform(285, -70));
            plusOneLiveShape_3_1.Transform = plusOneLiveShape_3_1Transform;
            plusOneLiveShape_3_1           = plusOneLiveShape_3_1.GetFlattenedPathGeometry();

            Geometry       plusScoresShape3_1          = GameShapes.gameShapes["plusScoresShape"];
            TransformGroup plusScoresShape3_1Transform = new TransformGroup();

            plusScoresShape3_1Transform.Children.Add(new TranslateTransform(260, 110));
            plusScoresShape3_1.Transform = plusScoresShape3_1Transform;
            plusScoresShape3_1           = plusScoresShape3_1.GetFlattenedPathGeometry();

            Geometry       plusScoresShape3_2          = GameShapes.gameShapes["plusScoresShape"];
            TransformGroup plusScoresShape3_2Transform = new TransformGroup();

            plusScoresShape3_2Transform.Children.Add(new TranslateTransform(750, -225));
            plusScoresShape3_2.Transform = plusScoresShape3_2Transform;
            plusScoresShape3_2           = plusScoresShape3_2.GetFlattenedPathGeometry();

            specialItems3.Add(new DecreaseHealthItem(1, Brushes.Red, new Pen(Brushes.Black, 2), spikesShape_3_1));
            specialItems3.Add(new DecreaseHealthItem(1, Brushes.Red, new Pen(Brushes.Black, 2), spikesShape_3_2));
            specialItems3.Add(new WallItem(Brushes.DarkKhaki, new Pen(Brushes.DarkGray, 2), wallShape3));
            specialItems3.Add(new IncreaseHealthItem(1, Brushes.BlueViolet, new Pen(Brushes.Black, 2), plusOneLiveShape_3_1));
            specialItems3.Add(new IncreasePlayerScoreItem(Brushes.Gold, new Pen(Brushes.Red, 2), plusScoresShape3_1));
            specialItems3.Add(new IncreasePlayerScoreItem(Brushes.Gold, new Pen(Brushes.Red, 2), plusScoresShape3_2));


            List <Enemy> enemies3 = new List <Enemy>();

            Geometry       smallEnemyShape_3_1          = GameShapes.gameShapes["smallEnemyShape"];
            TransformGroup smallEnemyShape_3_1Transform = new TransformGroup();

            smallEnemyShape_3_1Transform.Children.Add(new TranslateTransform(465, -140));
            smallEnemyShape_3_1.Transform = smallEnemyShape_3_1Transform;
            smallEnemyShape_3_1           = smallEnemyShape_3_1.GetFlattenedPathGeometry();

            Geometry       smallEnemyShape_3_2          = GameShapes.gameShapes["smallEnemyShape"];
            TransformGroup smallEnemyShape_3_2Transform = new TransformGroup();

            smallEnemyShape_3_2Transform.Children.Add(new TranslateTransform(1020, -250));
            smallEnemyShape_3_2.Transform = smallEnemyShape_3_2Transform;
            smallEnemyShape_3_2           = smallEnemyShape_3_2.GetFlattenedPathGeometry();

            Geometry       mediumEnemyShape3_1          = GameShapes.gameShapes["mediumEnemyShape"];
            TransformGroup mediumEnemyShape3_1Transform = new TransformGroup();

            mediumEnemyShape3_1Transform.Children.Add(new TranslateTransform(1070, 10));
            mediumEnemyShape3_1.Transform = mediumEnemyShape3_1Transform;
            mediumEnemyShape3_1           = mediumEnemyShape3_1.GetFlattenedPathGeometry();

            Geometry       mediumEnemyShape3_2          = GameShapes.gameShapes["mediumEnemyShape"];
            TransformGroup mediumEnemyShape3_2Transform = new TransformGroup();

            mediumEnemyShape3_2Transform.Children.Add(new TranslateTransform(100, 100));
            mediumEnemyShape3_2.Transform = mediumEnemyShape3_2Transform;
            mediumEnemyShape3_2           = mediumEnemyShape3_2.GetFlattenedPathGeometry();


            enemies3.Add(new SmallEnemy(smallEnemyShape_3_1));
            enemies3.Add(new SmallEnemy(smallEnemyShape_3_2));
            enemies3.Add(new MediumEnemy(mediumEnemyShape3_1));
            enemies3.Add(new MediumEnemy(mediumEnemyShape3_2));


            Geometry doorNextScreenShape3 = new LineGeometry(new Point(0, 0), new Point(0, -160))
                                            .GetWidenedPathGeometry(new Pen(Brushes.Black, 2));
            TransformGroup doorNextScreenShape3Transform = new TransformGroup();

            doorNextScreenShape3Transform.Children.Add(new TranslateTransform(1263, 100));
            doorNextScreenShape3.Transform = doorNextScreenShape3Transform;
            doorNextScreenShape3           = doorNextScreenShape3.GetFlattenedPathGeometry();
            DoorNextScreen doorNextScreen3 = new DoorNextScreen("screen_4", Brushes.Black, new Pen(Brushes.Black, 5), doorNextScreenShape3);

            screens.Add("screen_3", new Screen(new GroundLine(grounds3), doorNextScreen3, specialItems3, enemies3));


            // fourth screen
            Point[] oneSlice4 = new Point[] {
                new Point(0, 0),
                new Point(150, 0),
            };
            Point[][] grounds4 = new Point[][] { oneSlice4 };

            screens.Add("screen_4", new Screen(new GroundLine(grounds4)));
        }
コード例 #27
0
        private void RenderPath(WpfDrawingRenderer renderer)
        {
            WpfDrawingContext context = renderer.Context;

            SvgRenderingHint hint = _svgElement.RenderingHint;

            if (hint != SvgRenderingHint.Shape || hint == SvgRenderingHint.Clipping)
            {
                return;
            }
            var parentNode = _svgElement.ParentNode;

            // We do not directly render the contents of the clip-path, unless specifically requested...
            if (string.Equals(parentNode.LocalName, "clipPath") &&
                !context.RenderingClipRegion)
            {
                return;
            }

            SvgStyleableElement styleElm = (SvgStyleableElement)_svgElement;

            string sVisibility = styleElm.GetPropertyValue("visibility");
            string sDisplay    = styleElm.GetPropertyValue("display");

            if (string.Equals(sVisibility, "hidden") || string.Equals(sDisplay, "none"))
            {
                return;
            }

            DrawingGroup drawGroup = context.Peek();

            Debug.Assert(drawGroup != null);

            Geometry geometry = CreateGeometry(_svgElement, context.OptimizePath);

            string elementId    = this.GetElementName();
            string elementClass = this.GetElementClass();

            if (geometry != null && !geometry.IsEmpty())
            {
                context.UpdateBounds(geometry.Bounds);

//                SetClip(context);

                WpfSvgPaint fillPaint = new WpfSvgPaint(context, styleElm, "fill");

                string fileValue = styleElm.GetAttribute("fill");

                Brush brush            = fillPaint.GetBrush(geometry, _setBrushOpacity);
                bool  isFillTransmable = fillPaint.IsFillTransformable;

                WpfSvgPaint strokePaint = new WpfSvgPaint(context, styleElm, "stroke");
                Pen         pen         = strokePaint.GetPen(geometry, _setBrushOpacity);

                // By the SVG Specifications:
                // Keyword 'objectBoundingBox' should not be used when the geometry of the applicable
                // element has no width or no height, such as the case of a horizontal or vertical line,
                // even when the line has actual thickness when viewed due to having a non-zero stroke
                // width since stroke width is ignored for bounding box calculations. When the geometry
                // of the applicable element has no width or height and 'objectBoundingBox' is specified,
                // then the given effect (e.g., a gradient) will be ignored.
                if (pen != null && _isLineSegment && strokePaint.FillType == WpfFillType.Gradient)
                {
                    LineGeometry    lineGeometry = geometry as LineGeometry;
                    WpfGradientFill gradientFill = (WpfGradientFill)strokePaint.PaintServer;
                    if (gradientFill.IsUserSpace == false && lineGeometry != null)
                    {
                        bool invalidGrad = SvgObject.IsEqual(lineGeometry.EndPoint.X, lineGeometry.StartPoint.X) ||
                                           SvgObject.IsEqual(lineGeometry.EndPoint.Y, lineGeometry.StartPoint.Y);
                        if (invalidGrad)
                        {
                            // Brush is not likely inherited, we need to support fallback too
                            WpfSvgPaint fallbackPaint = strokePaint.WpfFallback;
                            if (fallbackPaint != null)
                            {
                                pen.Brush = fallbackPaint.GetBrush(geometry, _setBrushOpacity);
                            }
                            else
                            {
                                var scopePaint = strokePaint.GetScopeStroke();
                                if (scopePaint != null)
                                {
                                    if (scopePaint != strokePaint)
                                    {
                                        pen.Brush = scopePaint.GetBrush(geometry, _setBrushOpacity);
                                    }
                                    else
                                    {
                                        pen.Brush = null;
                                    }
                                }
                                else
                                {
                                    pen.Brush = null;
                                }
                            }
                        }
                    }
                }

                if (_paintContext != null)
                {
                    _paintContext.Fill   = fillPaint;
                    _paintContext.Stroke = strokePaint;
                    _paintContext.Tag    = geometry;
                }

                if (brush != null || pen != null)
                {
                    Transform transform = this.Transform;
                    if (transform != null && !transform.Value.IsIdentity)
                    {
                        geometry.Transform = transform;
                        if (brush != null && isFillTransmable)
                        {
                            Transform brushTransform = brush.Transform;
                            if (brushTransform == null || brushTransform == Transform.Identity)
                            {
                                brush.Transform = transform;
                            }
                            else
                            {
                                TransformGroup groupTransform = new TransformGroup();
                                groupTransform.Children.Add(brushTransform);
                                groupTransform.Children.Add(transform);
                                brush.Transform = groupTransform;
                            }
                        }
                        if (pen != null && pen.Brush != null)
                        {
                            Transform brushTransform = pen.Brush.Transform;
                            if (brushTransform == null || brushTransform == Transform.Identity)
                            {
                                pen.Brush.Transform = transform;
                            }
                            else
                            {
                                TransformGroup groupTransform = new TransformGroup();
                                groupTransform.Children.Add(brushTransform);
                                groupTransform.Children.Add(transform);
                                pen.Brush.Transform = groupTransform;
                            }
                        }
                    }
                    else
                    {
                        transform = null; // render any identity transform useless...
                    }

                    GeometryDrawing drawing = new GeometryDrawing(brush, pen, geometry);

                    if (!string.IsNullOrWhiteSpace(elementId) && !context.IsRegisteredId(elementId))
                    {
                        SvgObject.SetName(drawing, elementId);

                        context.RegisterId(elementId);

                        if (context.IncludeRuntime)
                        {
                            SvgObject.SetId(drawing, elementId);
                        }
                    }

                    if (!string.IsNullOrWhiteSpace(elementClass) && context.IncludeRuntime)
                    {
                        SvgObject.SetClass(drawing, elementClass);
                    }

                    Brush    maskBrush = this.Masking;
                    Geometry clipGeom  = this.ClipGeometry;
                    if (clipGeom != null || maskBrush != null)
                    {
                        //Geometry clipped = Geometry.Combine(geometry, clipGeom,
                        //    GeometryCombineMode.Exclude, null);

                        //if (clipped != null && !clipped.IsEmpty())
                        //{
                        //    geometry = clipped;
                        //}
                        DrawingGroup clipMaskGroup = new DrawingGroup();

                        Rect geometryBounds = geometry.Bounds;

                        if (clipGeom != null)
                        {
                            clipMaskGroup.ClipGeometry = clipGeom;

                            SvgUnitType clipUnits = this.ClipUnits;
                            if (clipUnits == SvgUnitType.ObjectBoundingBox)
                            {
                                Rect drawingBounds = geometryBounds;

                                if (transform != null)
                                {
                                    drawingBounds = transform.TransformBounds(drawingBounds);
                                }

                                TransformGroup transformGroup = new TransformGroup();

                                // Scale the clip region (at (0, 0)) and translate to the top-left corner of the target.
                                transformGroup.Children.Add(new ScaleTransform(drawingBounds.Width, drawingBounds.Height));
                                transformGroup.Children.Add(new TranslateTransform(drawingBounds.X, drawingBounds.Y));

                                clipGeom.Transform = transformGroup;
                            }
                            else
                            {
                                if (transform != null)
                                {
                                    clipGeom.Transform = transform;
                                }
                            }
                        }
                        if (maskBrush != null)
                        {
                            DrawingBrush drawingBrush = (DrawingBrush)maskBrush;

                            SvgUnitType maskUnits        = this.MaskUnits;
                            SvgUnitType maskContentUnits = this.MaskContentUnits;
                            if (maskUnits == SvgUnitType.ObjectBoundingBox)
                            {
                                Rect drawingBounds = geometryBounds;

                                if (transform != null)
                                {
                                    drawingBounds = transform.TransformBounds(drawingBounds);
                                }
                                DrawingGroup maskGroup = drawingBrush.Drawing as DrawingGroup;
                                if (maskGroup != null)
                                {
                                    DrawingCollection maskDrawings = maskGroup.Children;
                                    for (int i = 0; i < maskDrawings.Count; i++)
                                    {
                                        Drawing         maskDrawing  = maskDrawings[i];
                                        GeometryDrawing maskGeomDraw = maskDrawing as GeometryDrawing;
                                        if (maskGeomDraw != null)
                                        {
                                            if (maskGeomDraw.Brush != null)
                                            {
                                                ConvertColors(maskGeomDraw.Brush);
                                            }
                                            if (maskGeomDraw.Pen != null)
                                            {
                                                ConvertColors(maskGeomDraw.Pen.Brush);
                                            }
                                        }
                                    }
                                }

                                if (maskContentUnits == SvgUnitType.ObjectBoundingBox)
                                {
                                    TransformGroup transformGroup = new TransformGroup();

                                    // Scale the clip region (at (0, 0)) and translate to the top-left corner of the target.
                                    var scaleTransform = new ScaleTransform(drawingBounds.Width, drawingBounds.Height);
                                    transformGroup.Children.Add(scaleTransform);
                                    var translateTransform = new TranslateTransform(drawingBounds.X, drawingBounds.Y);
                                    transformGroup.Children.Add(translateTransform);

                                    Matrix scaleMatrix     = new Matrix();
                                    Matrix translateMatrix = new Matrix();

                                    scaleMatrix.Scale(drawingBounds.Width, drawingBounds.Height);
                                    translateMatrix.Translate(drawingBounds.X, drawingBounds.Y);

                                    Matrix matrix = Matrix.Multiply(scaleMatrix, translateMatrix);
                                    //maskBrush.Transform = transformGroup;
                                    maskBrush.Transform = new MatrixTransform(matrix);
                                }
                                else
                                {
                                    drawingBrush.Viewbox      = drawingBounds;
                                    drawingBrush.ViewboxUnits = BrushMappingMode.Absolute;

                                    drawingBrush.Stretch = Stretch.Uniform;

                                    drawingBrush.Viewport      = drawingBounds;
                                    drawingBrush.ViewportUnits = BrushMappingMode.Absolute;
                                }
                            }
                            else
                            {
                                if (transform != null)
                                {
                                    maskBrush.Transform = transform;
                                }
                            }

                            clipMaskGroup.OpacityMask = maskBrush;
                        }

                        clipMaskGroup.Children.Add(drawing);
                        drawGroup.Children.Add(clipMaskGroup);
                    }
                    else
                    {
                        drawGroup.Children.Add(drawing);
                    }
                }
            }

            // If this is not the child of a "marker", then try rendering a marker...
            if (!string.Equals(parentNode.LocalName, "marker"))
            {
                RenderMarkers(renderer, styleElm, context);
            }
        }
コード例 #28
0
        internal void SetBrush()
        {
            if (!_UpdateBrush)
            {
                return;
            }

            this._BrushSetInternally = true;

            // retain old opacity
            double         opacity = 1;
            TransformGroup tempTG  = null;

            if (this.Brush != null)
            {
                opacity = this.Brush.Opacity;
                tempTG  = Brush.Transform as TransformGroup;
            }

            switch (BrushType)
            {
            //case BrushTypes.None: Brush = null; break;

            case BrushTypes.Solid:

                Brush = new SolidColorBrush(this.Color);

                break;

            case BrushTypes.Linear:

                var brush = new LinearGradientBrush();
                foreach (GradientStop g in Gradients)
                {
                    brush.GradientStops.Add(new GradientStop(g.Color, g.Offset));
                }
                brush.StartPoint   = new Point(this.StartX, this.StartY);
                brush.EndPoint     = new Point(this.EndX, this.EndY);
                brush.MappingMode  = this.MappingMode;
                brush.SpreadMethod = this.SpreadMethod;
                Brush = brush;

                break;


            case BrushTypes.Radial:

                var brush1 = new RadialGradientBrush();
                foreach (GradientStop g in Gradients)
                {
                    brush1.GradientStops.Add(new GradientStop(g.Color, g.Offset));
                }
                brush1.GradientOrigin = new Point(this.GradientOriginX, this.GradientOriginY);
                brush1.Center         = new Point(this.CenterX, this.CenterY);
                brush1.RadiusX        = this.RadiusX;
                brush1.RadiusY        = this.RadiusY;
                brush1.MappingMode    = this.MappingMode;
                brush1.SpreadMethod   = this.SpreadMethod;
                Brush = brush1;

                break;
            }

            /*
             * if (this.BrushType != BrushTypes.None)
             * {
             *  this.Brush.Opacity = opacity;  // retain old opacity
             *  if (tempTG != null)
             *      this.Brush.Transform = tempTG;
             * }
             */

            this._BrushSetInternally = false;
        }
コード例 #29
0
        public override bool Draw(bool checkDrawTimer)
        {
            if (MainWindow.shiftPressed)
            {
                theCanvas.Cursor = Cursors.Hand;
            }
            else
            {
                theCanvas.Cursor = Cursors.Arrow;
            }
            if (!base.Draw(checkDrawTimer))
            {
                return(false);
            }

            Module2DSim parent = (Module2DSim)base.ParentModule;

            //theCanvas.Children.RemoveRange(1, theCanvas.Children.Count-1);
            theCanvas.Children.Clear();
            Point windowSize   = new Point(theCanvas.ActualWidth, theCanvas.ActualHeight);
            Point windowCenter = new Point(windowSize.X / 2, windowSize.Y / 2);

            windowCenter += pan;
            float scale = (float)Math.Min(windowSize.X, windowSize.Y) * zoom;

            if (scale == 0)
            {
                return(false);
            }

            TransformGroup tg = new TransformGroup();

            tg.Children.Add(new RotateTransform(90));
            tg.Children.Add(new ScaleTransform(scale, -scale, 0, 0));
            tg.Children.Add(new TranslateTransform(windowCenter.X, windowCenter.Y));
            theCanvas.RenderTransform = tg;


            //add a background
            Rectangle r = new Rectangle()
            {
                Height = parent.boundarySize * 2, Width = parent.boundarySize * 2, Stroke = Brushes.AliceBlue, Fill = Brushes.AliceBlue
            };

            Canvas.SetLeft(r, -parent.boundarySize);
            Canvas.SetTop(r, -parent.boundarySize);
            theCanvas.Children.Add(r);

            //draw the camera track...
            Polyline p = new Polyline();

            p.StrokeThickness = 1 / scale;
            p.Stroke          = Brushes.Pink;
            for (int i = 0; i < parent.entityTrack.Count; i++)
            {
                p.Points.Add(
                    new Point(
                        parent.entityTrack[i].X,
                        parent.entityTrack[i].Y
                        )
                    );
            }
            theCanvas.Children.Add(p);

            //draw the objects
            for (int i = 0; i < parent.objects.Count; i++)
            {
                if (parent.objects[i].theColor != Colors.Black && parent.texture != 0)
                {
                    theCanvas.Children.Add(new Line
                    {
                        X1 = parent.objects[i].P1.X,
                        X2 = parent.objects[i].P2.X,
                        Y1 = parent.objects[i].P1.Y,
                        Y2 = parent.objects[i].P2.Y,
                        StrokeThickness = 4 / scale,
                        Stroke          = new SolidColorBrush(parent.objects[i].theColor),
                    });
                    //dash the line
                    PointPlus P1    = new PointPlus(parent.objects[i].P1);
                    PointPlus P2    = new PointPlus(parent.objects[i].P2);
                    PointPlus delta = P2 - P1;
                    delta.R = .1f;
                    Segment s = new Segment(P1, P2, parent.objects[i].theColor);
                    for (int j = 1; j < 1 + s.Length * 10; j += 2)
                    {
                        PointPlus PStart = new PointPlus((Point)(P1.V + j * delta.V));
                        PointPlus PEnd   = new PointPlus((Point)(P1.V + (j + .5f) * delta.V));
                        theCanvas.Children.Add(new Line
                        {
                            X1 = PStart.X,
                            X2 = PEnd.X,
                            Y1 = PStart.Y,
                            Y2 = PEnd.Y,
                            StrokeThickness = 4 / scale,
                            Stroke          = new SolidColorBrush(Colors.AliceBlue),
                        });
                    }
                }
                else
                {
                    theCanvas.Children.Add(new Line
                    {
                        X1 = parent.objects[i].P1.X,
                        X2 = parent.objects[i].P2.X,
                        Y1 = parent.objects[i].P1.Y,
                        Y2 = parent.objects[i].P2.Y,
                        StrokeThickness = 4 / scale,
                        Stroke          = new SolidColorBrush(parent.objects[i].theColor),
                    });
                }
            }

            //draw the arms...
            if (parent.armActual.Length == 2)
            {
                for (int i = 0; i < parent.armActual.Length; i++)
                {
                    PointPlus c = new PointPlus
                    {
                        P = (Point)(parent.armActual[i] - parent.entityPosition)
                    };
                    double sa = c.R * .85; //lower arm lengths
                    //double sb = (c.R-sa) * 4; //upper arm lengths
                    //double sa = .45; // lower arm lengths
                    double sb = .3; // upper arm lengths
                    float  a  = (float)(Math.Acos((sb * sb + c.R * c.R - sa * sa) / (2 * sb * c.R)));
                    if (!Double.IsNaN(a))

                    {
                        PointPlus pa = new PointPlus
                        {
                            R     = (float)sb,
                            Theta = c.Theta
                        };
                        if (i == 0)
                        {
                            pa.Theta += a;
                        }
                        else
                        {
                            pa.Theta -= a;
                        }
                        pa.P = (Point)(pa.P + (Vector)parent.entityPosition);
                        theCanvas.Children.Add(new Line
                        {
                            X1 = parent.entityPosition.X,
                            Y1 = parent.entityPosition.Y,
                            X2 = pa.P.X,
                            Y2 = pa.P.Y,
                            StrokeThickness = 2 / scale,
                            Stroke          = Brushes.Black
                        });
                        theCanvas.Children.Add(new Line
                        {
                            X1 = pa.P.X,
                            Y1 = pa.P.Y,
                            X2 = parent.armActual[i].X,
                            Y2 = parent.armActual[i].Y,
                            StrokeThickness = 2 / scale,
                            Stroke          = Brushes.Black
                        });
                    }
                }
            }

            //draw the current field of view
            if ((bool)cbArcs.IsChecked)
            {
                for (int i = 0; i < parent.currentView0.Count; i++)
                {
                    try //TODO lock the list
                    {
                        theCanvas.Children.Add(new Line
                        {
                            X1 = parent.currentView0[i].P1.X,
                            Y1 = parent.currentView0[i].P1.Y,
                            X2 = parent.currentView0[i].P1.X,
                            Y2 = parent.currentView0[i].P1.Y,
                            StrokeThickness    = 3 / scale,
                            StrokeEndLineCap   = PenLineCap.Round,
                            StrokeStartLineCap = PenLineCap.Round,
                            Stroke             = new SolidColorBrush(parent.currentView0[i].theColor)
                        });
                    }
                    catch { }
                }
                for (int i = 0; i < parent.currentView1.Count; i++)
                {
                    try //another thread might mess the array up TODO, lock the object list
                    {
                        theCanvas.Children.Add(new Line
                        {
                            X1 = parent.currentView1[i].P1.X,
                            Y1 = parent.currentView1[i].P1.Y,
                            X2 = parent.currentView1[i].P1.X,
                            Y2 = parent.currentView1[i].P1.Y,
                            StrokeThickness    = 3 / scale,
                            StrokeEndLineCap   = PenLineCap.Round,
                            StrokeStartLineCap = PenLineCap.Round,
                            Stroke             = new SolidColorBrush(parent.currentView1[i].theColor)
                        });
                    }
                    catch { }
                }
            }
            ////draw the body...it's a transparent gif
            Image body = new Image()
            {
                Source = new BitmapImage(new Uri("/Resources/entity.png", UriKind.Relative)),
                Width  = 2 * parent.bodyRadius,
                Height = 2 * parent.bodyRadius
            };
            TransformGroup tg1 = new TransformGroup();

            tg1.Children.Add(new TranslateTransform(-parent.bodyRadius, -parent.bodyRadius));
            tg1.Children.Add(new RotateTransform(90 + parent.entityDirection1 * 180 / Math.PI));
            body.RenderTransform = tg1;
            Canvas.SetLeft(body, parent.entityPosition.X);
            Canvas.SetTop(body, parent.entityPosition.Y);
            theCanvas.Children.Add(body);

            return(true);
        }
コード例 #30
0
        private TextBlock GetTextBlock(Polygon polygon)
        {
            TextBlock textBlock = new TextBlock();

            textBlock.HorizontalAlignment = HorizontalAlignment.Center;
            textBlock.VerticalAlignment   = VerticalAlignment.Center;
            textBlock.TextAlignment       = TextAlignment.Left;
            textBlock.TextWrapping        = TextWrapping.Wrap;

            textBlock.Inlines.Add(new Run()
            {
                Text = this.Name
            });

            textBlock.FontFamily = new FontFamily("Arial");
            textBlock.Foreground = new SolidColorBrush(ColorFromString.ToColor("#AAFCFA"));


            Canvas.SetLeft(textBlock, this.GetCenterLeft() - textBlock.ActualWidth / 2);
            Canvas.SetTop(textBlock, this.GetCenterTop() - textBlock.ActualHeight / 2);
            Canvas.SetLeft(textBlock, Canvas.GetLeft(textBlock));
            Canvas.SetTop(textBlock, Canvas.GetTop(textBlock));
            Canvas.SetZIndex(textBlock, 1100);

            double centerX = textBlock.ActualWidth / 2;
            double centerY = textBlock.ActualHeight / 2;

            TransformGroup transform = new TransformGroup();

            if (this.IsRotate)
            {
                RotateTransform rotate = new RotateTransform();
                rotate.CenterY = centerY;
                rotate.CenterX = centerX;
                rotate.Angle   = 90;
                transform.Children.Add(rotate);
            }


            double scaleRate = 1;

            if (polygon.Points.Count == 4)
            {
                double polygonX = Math.Min(Math.Abs(polygon.Points[1].X - polygon.Points[0].X), Math.Abs(polygon.Points[2].X - polygon.Points[3].X));
                double polygonY = Math.Min(Math.Abs(polygon.Points[3].Y - polygon.Points[0].Y), Math.Abs(polygon.Points[2].Y - polygon.Points[1].Y));

                double newpolygonX = polygonX * GoldenSectionRate;
                double newpolygonY = polygonY * GoldenSectionRate;

                double textX = textBlock.ActualWidth;
                double textY = textBlock.ActualHeight;

                if (this.IsRotate)
                {
                    textY = textBlock.ActualWidth;
                    textX = textBlock.ActualHeight;
                }

                if (newpolygonX / textX <= newpolygonY / textY)
                {
                    scaleRate = newpolygonX / textX;
                }
                else
                {
                    scaleRate = newpolygonY / textY;
                }
            }

            ScaleTransform scale = new ScaleTransform();

            scale.CenterX = centerX;
            scale.CenterY = centerY;
            scale.ScaleX  = scaleRate;
            scale.ScaleY  = scaleRate;

            transform.Children.Add(scale);

            textBlock.RenderTransform = transform;
            textBlock.Tag             = this;


            textBlock.MouseEnter += new MouseEventHandler(textBlock_OnMouseEnter);

            if (!string.IsNullOrEmpty(this.Comment))
            {
                ToolTipService.SetToolTip(textBlock, this.Comment);
            }

            return(textBlock);
        }
コード例 #31
0
        protected override void OnViewportChanged(ViewportChangedEventArgs e)
        {
            var projection = ParentMap.MapProjection;

            if (!double.IsNaN(projection.LongitudeScale))
            {
                if (path == null)
                {
                    path = new Path
                    {
                        Data = new PathGeometry()
                    };

                    path.SetBinding(Shape.StrokeProperty,
                                    GetBindingExpression(StrokeProperty)?.ParentBinding ??
                                    new Binding
                    {
                        Source = this,
                        Path   = new PropertyPath("Stroke")
                    });

                    path.SetBinding(Shape.StrokeThicknessProperty,
                                    GetBindingExpression(StrokeThicknessProperty)?.ParentBinding ??
                                    new Binding
                    {
                        Source = this,
                        Path   = new PropertyPath("StrokeThickness")
                    });

                    Children.Add(path);
                }

                var bounds       = projection.ViewportRectToBoundingBox(new Rect(0d, 0d, ParentMap.RenderSize.Width, ParentMap.RenderSize.Height));
                var lineDistance = GetLineDistance();

                var labelStart = new Location(
                    Math.Ceiling(bounds.South / lineDistance) * lineDistance,
                    Math.Ceiling(bounds.West / lineDistance) * lineDistance);

                var labelEnd = new Location(
                    Math.Floor(bounds.North / lineDistance) * lineDistance,
                    Math.Floor(bounds.East / lineDistance) * lineDistance);

                var lineStart = new Location(
                    Math.Min(Math.Max(labelStart.Latitude - lineDistance, -projection.MaxLatitude), projection.MaxLatitude),
                    labelStart.Longitude - lineDistance);

                var lineEnd = new Location(
                    Math.Min(Math.Max(labelEnd.Latitude + lineDistance, -projection.MaxLatitude), projection.MaxLatitude),
                    labelEnd.Longitude + lineDistance);

                if (!lineStart.Equals(graticuleStart) || !lineEnd.Equals(graticuleEnd))
                {
                    graticuleStart = lineStart;
                    graticuleEnd   = lineEnd;

                    var geometry = (PathGeometry)path.Data;
                    geometry.Figures.Clear();
                    geometry.Transform = projection.ViewportTransform;

                    for (var lat = labelStart.Latitude; lat <= bounds.North; lat += lineDistance)
                    {
                        var figure = new PathFigure
                        {
                            StartPoint = projection.LocationToPoint(new Location(lat, lineStart.Longitude)),
                            IsClosed   = false,
                            IsFilled   = false
                        };

                        figure.Segments.Add(new LineSegment
                        {
                            Point = projection.LocationToPoint(new Location(lat, lineEnd.Longitude)),
                        });

                        geometry.Figures.Add(figure);
                    }

                    for (var lon = labelStart.Longitude; lon <= bounds.East; lon += lineDistance)
                    {
                        var figure = new PathFigure
                        {
                            StartPoint = projection.LocationToPoint(new Location(lineStart.Latitude, lon)),
                            IsClosed   = false,
                            IsFilled   = false
                        };

                        figure.Segments.Add(new LineSegment
                        {
                            Point = projection.LocationToPoint(new Location(lineEnd.Latitude, lon)),
                        });

                        geometry.Figures.Add(figure);
                    }

                    var labelFormat = GetLabelFormat(lineDistance);
                    var childIndex  = 1; // 0 for Path

                    for (var lat = labelStart.Latitude; lat <= bounds.North; lat += lineDistance)
                    {
                        for (var lon = labelStart.Longitude; lon <= bounds.East; lon += lineDistance)
                        {
                            TextBlock label;

                            if (childIndex < Children.Count)
                            {
                                label = (TextBlock)Children[childIndex];
                            }
                            else
                            {
                                var renderTransform = new TransformGroup();
                                renderTransform.Children.Add(new TranslateTransform());
                                renderTransform.Children.Add(ParentMap.RotateTransform);
                                renderTransform.Children.Add(new TranslateTransform());

                                label = new TextBlock
                                {
                                    RenderTransform = renderTransform
                                };

                                label.SetBinding(TextBlock.ForegroundProperty,
                                                 GetBindingExpression(ForegroundProperty)?.ParentBinding ??
                                                 new Binding
                                {
                                    Source = this,
                                    Path   = new PropertyPath("Foreground")
                                });

                                Children.Add(label);
                            }

                            childIndex++;

                            if (FontFamily != null)
                            {
                                label.FontFamily = FontFamily;
                            }

                            label.FontSize    = FontSize;
                            label.FontStyle   = FontStyle;
                            label.FontStretch = FontStretch;
                            label.FontWeight  = FontWeight;
                            label.Text        = GetLabelText(lat, labelFormat, "NS") + "\n" + GetLabelText(Location.NormalizeLongitude(lon), labelFormat, "EW");
                            label.Tag         = new Location(lat, lon);
                            label.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));

                            var translateTransform = (TranslateTransform)((TransformGroup)label.RenderTransform).Children[0];
                            translateTransform.X = StrokeThickness / 2d + 2d;
                            translateTransform.Y = -label.DesiredSize.Height / 2d;
                        }
                    }

                    while (Children.Count > childIndex)
                    {
                        Children.RemoveAt(Children.Count - 1);
                    }
                }

                // don't use MapPanel.Location because labels may be at more than 180° distance from map center

                for (int i = 1; i < Children.Count; i++)
                {
                    var label             = (TextBlock)Children[i];
                    var location          = (Location)label.Tag;
                    var viewportTransform = (TranslateTransform)((TransformGroup)label.RenderTransform).Children[2];
                    var viewportPosition  = projection.LocationToViewportPoint(location);
                    viewportTransform.X = viewportPosition.X;
                    viewportTransform.Y = viewportPosition.Y;
                }
            }
            else if (path != null)
            {
                path           = null;
                graticuleStart = null;
                graticuleEnd   = null;

                Children.Clear();
            }

            base.OnViewportChanged(e);
        }
コード例 #32
0
        private void drawBrushAttachment(Vec attachmentCenter, Canvas c)
        {
            var filterLinkViewModel = DataContext as FilterLinkViewModel;
            var sourceCount         = filterLinkViewModel.FilterLinkModels.Count(lvm => lvm.LinkType == LinkType.Brush);

            var c1 = new Rectangle();

            c1.Width  = _attachmentRectHalfSize * 2;
            c1.Height = _attachmentRectHalfSize * 2;

            c1.RenderTransform = new TranslateTransform
            {
                X = attachmentCenter.X - _attachmentRectHalfSize,
                Y = attachmentCenter.Y - _attachmentRectHalfSize
            };
            c.Children.Add(c1);

            c1.Fill            = _lightBrush;
            c1.Stroke          = _lightBrush;
            c1.StrokeThickness = 2;

            var brushCanvas = new Canvas();
            var p1          = new Path();

            p1.Fill = _lightBrush;
            var b = new Binding
            {
                Source = "m 0,0 c 0.426,0 0.772,-0.346 0.772,-0.773 0,-0.426 -0.346,-0.772 -0.772,-0.772 -0.427,0 -0.773,0.346 -0.773,0.772 C -0.773,-0.346 -0.427,0 0,0 m -9.319,11.674 c 0,0 7.188,0.868 7.188,-7.187 l 0,-5.26 c 0,-1.618 1.175,-1.888 2.131,-1.888 0,0 1.914,-0.245 1.871,1.87 l 0,5.246 c 0,0 0.214,7.219 7.446,7.219 l 0,2.21 -18.636,0 0,-2.21 z"
            };

            BindingOperations.SetBinding(p1, Path.DataProperty, b);
            var tg = new TransformGroup();

            tg.Children.Add(new ScaleTransform {
                ScaleX = 1, ScaleY = -1
            });
            tg.Children.Add(new TranslateTransform {
                X = 9.3, Y = 26
            });
            p1.RenderTransform = tg;
            brushCanvas.Children.Add(p1);

            var p2 = new Path();

            p2.Fill = _lightBrush;
            b       = new Binding
            {
                Source = "m 0,0 0,-0.491 0,-4.316 18.636,0 0,3.58 0,1.227 0,5.333 L 0,5.333 0,0 z"
            };
            BindingOperations.SetBinding(p2, Path.DataProperty, b);
            tg = new TransformGroup();
            tg.Children.Add(new ScaleTransform {
                ScaleX = 1, ScaleY = -1
            });
            tg.Children.Add(new TranslateTransform {
                X = 0, Y = 6
            });
            p2.RenderTransform = tg;
            brushCanvas.Children.Add(p2);

            //BrushIcon brushIcon = new BrushIcon();
            //brushIcon.SetBrush(sourceCount > 1 && false ? Destination.FaintBrush : Destination.Brush);
            Matrix mat = Mat.Translate(
                attachmentCenter.X - _attachmentRectHalfSize + 7,
                attachmentCenter.Y - _attachmentRectHalfSize + 7) * Mat.Scale(0.80, 0.80) * Mat.Rotate(new Deg(45), new Pt(10, 10));

            brushCanvas.RenderTransform = new MatrixTransform {
                Matrix = mat
            };
            c.Children.Add(brushCanvas);

            var t = attachmentCenter - new Vec(_attachmentRectHalfSize, _attachmentRectHalfSize);
            var r = new Rct(new Pt(t.X, t.Y),
                            new Vec(_attachmentRectHalfSize * 2, _attachmentRectHalfSize * 2));

            _linkViewGeometry = r.GetPolygon().Buffer(3);
        }
コード例 #33
0
        /// <summary>
        /// Walks the Transform and returns the corresponding matrix.
        /// </summary>
        /// <param name="transform">The transform to create a matrix for.
        /// </param>
        /// <returns>The matrix calculated from the transform.</returns>
        private Matrix GetTransformMatrix(Transform transform)
        {
            if (null != transform)
            {
                // WPF equivalent of this entire method (why oh why only WPF...):
                // return transform.Value;

                // Process the TransformGroup
                TransformGroup transformGroup = transform as TransformGroup;
                if (null != transformGroup)
                {
                    Matrix groupMatrix = Matrix.Identity;

                    foreach (Transform child in transformGroup.Children)
                    {
                        groupMatrix = MatrixMultiply(groupMatrix, GetTransformMatrix(child));
                    }
                    return(groupMatrix);
                }

                // Process the RotateTransform
                RotateTransform rotateTransform = transform as RotateTransform;
                if (null != rotateTransform)
                {
                    double angle        = rotateTransform.Angle;
                    double angleRadians = (2 * Math.PI * angle) / 360;
                    double sine         = Math.Sin(angleRadians);
                    double cosine       = Math.Cos(angleRadians);
                    return(new Matrix(cosine, sine, -sine, cosine, 0, 0));
                }

                // Process the ScaleTransform
                ScaleTransform scaleTransform = transform as ScaleTransform;
                if (null != scaleTransform)
                {
                    double scaleX = scaleTransform.ScaleX;
                    double scaleY = scaleTransform.ScaleY;
                    return(new Matrix(scaleX, 0, 0, scaleY, 0, 0));
                }

                // Process the SkewTransform
                SkewTransform skewTransform = transform as SkewTransform;
                if (null != skewTransform)
                {
                    double angleX        = skewTransform.AngleX;
                    double angleY        = skewTransform.AngleY;
                    double angleXRadians = (2 * Math.PI * angleX) / 360;
                    double angleYRadians = (2 * Math.PI * angleY) / 360;
                    return(new Matrix(1, angleYRadians, angleXRadians, 1, 0, 0));
                }

                // Process the MatrixTransform
                MatrixTransform matrixTransform = transform as MatrixTransform;
                if (null != matrixTransform)
                {
                    return(matrixTransform.Matrix);
                }

                if (transform is CompositeTransform)
                {
                    throw new NotSupportedException("CompositeTransforms are not supported (yet) by the LayoutTransformControl.");
                }

                // TranslateTransform has no effect in LayoutTransform
            }

            // Fall back to no-op transformation
            return(Matrix.Identity);
        }
コード例 #34
0
        protected override void OnViewportChanged()
        {
            var bounds = ParentMap.ViewportTransform.Inverse.TransformBounds(new Rect(new Point(), ParentMap.RenderSize));
            var start = ParentMap.MapTransform.Transform(new Point(bounds.X, bounds.Y));
            var end = ParentMap.MapTransform.Transform(new Point(bounds.X + bounds.Width, bounds.Y + bounds.Height));
            var minSpacing = MinLineSpacing * 360d / (Math.Pow(2d, ParentMap.ZoomLevel) * 256d);
            var spacing = LineSpacings[LineSpacings.Length - 1];

            if (spacing >= minSpacing)
            {
                spacing = LineSpacings.FirstOrDefault(s => s >= minSpacing);
            }

            var labelStart = new Location(
                Math.Ceiling(start.Latitude / spacing) * spacing,
                Math.Ceiling(start.Longitude / spacing) * spacing);

            var labelEnd = new Location(
                Math.Floor(end.Latitude / spacing) * spacing,
                Math.Floor(end.Longitude / spacing) * spacing);

            var lineStart = new Location(
                Math.Min(Math.Max(labelStart.Latitude - spacing, -ParentMap.MapTransform.MaxLatitude), ParentMap.MapTransform.MaxLatitude),
                labelStart.Longitude - spacing);

            var lineEnd = new Location(
                Math.Min(Math.Max(labelEnd.Latitude + spacing, -ParentMap.MapTransform.MaxLatitude), ParentMap.MapTransform.MaxLatitude),
                labelEnd.Longitude + spacing);

            if (!lineStart.Equals(graticuleStart) || !lineEnd.Equals(graticuleEnd))
            {
                graticuleStart = lineStart;
                graticuleEnd = lineEnd;

                var geometry = (PathGeometry)path.Data;
                geometry.Figures.Clear();
                geometry.Transform = ParentMap.ViewportTransform;

                for (var lat = labelStart.Latitude; lat <= end.Latitude; lat += spacing)
                {
                    var figure = new PathFigure
                    {
                        StartPoint = ParentMap.MapTransform.Transform(new Location(lat, lineStart.Longitude)),
                        IsClosed = false,
                        IsFilled = false
                    };

                    figure.Segments.Add(new LineSegment
                    {
                        Point = ParentMap.MapTransform.Transform(new Location(lat, lineEnd.Longitude)),
                    });

                    geometry.Figures.Add(figure);
                }

                for (var lon = labelStart.Longitude; lon <= end.Longitude; lon += spacing)
                {
                    var figure = new PathFigure
                    {
                        StartPoint = ParentMap.MapTransform.Transform(new Location(lineStart.Latitude, lon)),
                        IsClosed = false,
                        IsFilled = false
                    };

                    figure.Segments.Add(new LineSegment
                    {
                        Point = ParentMap.MapTransform.Transform(new Location(lineEnd.Latitude, lon)),
                    });

                    geometry.Figures.Add(figure);
                }

                var childIndex = 1; // 0 for Path
                var format = spacing < 1d ? "{0} {1}°{2:00}'" : "{0} {1}°";

                for (var lat = labelStart.Latitude; lat <= end.Latitude; lat += spacing)
                {
                    for (var lon = labelStart.Longitude; lon <= end.Longitude; lon += spacing)
                    {
                        TextBlock label;

                        if (childIndex < Children.Count)
                        {
                            label = (TextBlock)Children[childIndex];
                        }
                        else
                        {
                            var renderTransform = new TransformGroup();
                            renderTransform.Children.Add(new TranslateTransform());
                            renderTransform.Children.Add(ParentMap.RotateTransform);
                            renderTransform.Children.Add(new TranslateTransform());

                            label = new TextBlock
                            {
                                RenderTransform = renderTransform
                            };

                            label.SetBinding(TextBlock.ForegroundProperty, new Binding
                            {
                                Source = this,
                                Path = new PropertyPath("Foreground")
                            });

                            Children.Add(label);
                        }

                        childIndex++;

                        if (FontFamily != null)
                        {
                            label.FontFamily = FontFamily;
                        }

                        label.FontSize = FontSize;
                        label.FontStyle = FontStyle;
                        label.FontStretch = FontStretch;
                        label.FontWeight = FontWeight;
                        label.Text = string.Format("{0}\n{1}", CoordinateString(lat, format, "NS"), CoordinateString(Location.NormalizeLongitude(lon), format, "EW"));
                        label.Tag = new Location(lat, lon);
                        label.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));

                        var translateTransform = (TranslateTransform)((TransformGroup)label.RenderTransform).Children[0];
                        translateTransform.X = StrokeThickness / 2d + 2d;
                        translateTransform.Y = -label.DesiredSize.Height / 2d;
                    }
                }

                while (Children.Count > childIndex)
                {
                    Children.RemoveAt(Children.Count - 1);
                }
            }

            // don't use MapPanel.Location because labels may be at more than 180° distance from map center

            for (int i = 1; i < Children.Count; i++)
            {
                var label = (TextBlock)Children[i];
                var location = (Location)label.Tag;
                var viewportTransform = (TranslateTransform)((TransformGroup)label.RenderTransform).Children[2];
                var viewportPosition = ParentMap.LocationToViewportPoint(location);
                viewportTransform.X = viewportPosition.X;
                viewportTransform.Y = viewportPosition.Y;
            }

            base.OnViewportChanged();
        }
コード例 #35
0
ファイル: Program.cs プロジェクト: KarimLUCCIN/Fbx-Breaker
 public override string ResolveOutputPath(string id, TransformGroup transform)
 {
     return BasePath + id + ".x";
 }