示例#1
0
    public void drawBullet(Bullet theBullet)
    {
        gameCanvas.Children.Add(theBullet.getBulletShape());

        TranslateTransform initialTransform = new TranslateTransform(theBullet.getBulletX(), theBullet.getBulletY());
        theBullet.getBulletShape().RenderTransform = initialTransform;
    }
示例#2
0
    public void drawAsteroid(MovableGameEntity theAsteroid)
    {
        Polygon newPolygon = new Polygon();
        theAsteroid.setEntityShape(newPolygon);
        theAsteroid.entityShape.Name = "Asteroid" + this.asteroidsAdded;
        this.asteroidsAdded += 1;
        theAsteroid.entityShape.Stroke = Brushes.White;
        theAsteroid.entityShape.StrokeThickness = 2;
        theAsteroid.entityShape.Points = theAsteroid.getEntityDimensions();
        gameCanvas.Children.Add(theAsteroid.entityShape);

        TranslateTransform initialTransform = new TranslateTransform(theAsteroid.getEntityCenterX(), theAsteroid.getEntityCenterY());
        theAsteroid.entityShape.RenderTransform = initialTransform;
    }
            override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            ContentDragTransform = (TranslateTransform)GetTemplateChild("ContentDragTransform");
            LeftTransform = (TranslateTransform)GetTemplateChild("LeftTransform");
            RightTransform = (TranslateTransform)GetTemplateChild("RightTransform");

            LeftContainer = (Border)GetTemplateChild("LeftContainer");
            RightContainer = (Border)GetTemplateChild("RightContainer");

            DragBackground = (Grid)GetTemplateChild("DragBackground");
            DragClip = (RectangleGeometry)GetTemplateChild("DragClip");
            DragClipTransform = (TranslateTransform)GetTemplateChild("DragClipTransform");
            DragContainer = (Border)GetTemplateChild("DragContainer");
        }
		public override void OnApplyTemplate()
#endif
		{
			base.OnApplyTemplate();

			ApplyPlatformFeatures();

			_horizontalThumb = GetTemplateChild(HorizontalThumbName) as Thumb;
			_horizontalTrack = GetTemplateChild(HorizontalTrackName) as Rectangle;
			_horizontalFill = GetTemplateChild(HorizontalFillName) as Rectangle;
			_horizontalRectangleGeometry = GetTemplateChild(HorizontalRectangleGeometryName) as RectangleGeometry;
			_horizontalThumbTranslateTransform = GetTemplateChild(HorizontalThumbTranslateTransformName) as TranslateTransform;

			SyncValueAndPosition(Value, Value);

			_isLayoutInit = true;
		}
示例#5
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;
	}
        private Transform GetAspectRatioTransform(SvgPreserveAspectRatio spar,
                                                  SvgRect sourceBounds, SvgRect elementBounds)
        {
            double[] transformArray = spar.FitToViewBox(sourceBounds, elementBounds);

            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);

            // Cacxa
            if (this.Transform != null)
            {
                if (!scaleX.Equals(1.0) && !this.Transform.Value.OffsetX.Equals(0.0))
                {
                    translateX = translateX + this.Transform.Value.OffsetX * (1 - scaleX);
                }
                if (!scaleY.Equals(1.0) && !this.Transform.Value.OffsetY.Equals(0.0))
                {
                    translateY = translateY + this.Transform.Value.OffsetY * (1 - scaleY);
                }
            }

            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.Value.IsIdentity ? null : translateMatrix);
            }

            if (scaleMatrix != null)
            {
                return(scaleMatrix.Value.IsIdentity ? null : scaleMatrix);
            }

            return(null);
        }
示例#7
0
 /// <summary>
 /// Initializes a new instance of <see cref="AnimationPanel.ItemAnimationData"/>.
 /// </summary>
 public ItemAnimationData()
 {
     randomSeed = Random.NextDouble();
     transform  = new TranslateTransform();
 }
        protected override void Init()
        {
            SetBaseView();


            ScaleTransform     translation          = new ScaleTransform(1, 1);
            TranslateTransform translationTranslate = new TranslateTransform(0, 0);

            dauX = new DoubleAnimationUsingKeyFrames();
            dauY = 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 ScaleTransform(1, 1);

                Win.RegisterName(translation.GetHashCode().ToString(), translation);
                tg.Children.Add(translation);

                Win.RegisterName(translationTranslate.GetHashCode().ToString(), translationTranslate);
                tg.Children.Add(translationTranslate);


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

                foreach (var item in tg.Children)
                {
                    translationTranslate = item as TranslateTransform;
                    if (translationTranslate != null)
                    {
                        break;
                    }
                }

                if (translation != null)
                {
                    var tex = translation.GetValue(FrameworkElement.NameProperty);
                    if (tex != null && tex.ToString() != "")
                    {
                    }
                    else
                    {
                        Win.RegisterName(translation.GetHashCode().ToString(), translation);
                    }
                }
                else
                {
                    translation = new ScaleTransform(1, 1);

                    Win.RegisterName(translation.GetHashCode().ToString(), translation);
                    tg.Children.Add(translation);
                    Element.RenderTransform = tg;
                }

                if (translationTranslate != null)
                {
                    var tex = translationTranslate.GetValue(FrameworkElement.NameProperty);
                    if (tex != null && tex.ToString() != "")
                    {
                    }
                    else
                    {
                        Win.RegisterName(translationTranslate.GetHashCode().ToString(), translationTranslate);
                    }
                }
                else
                {
                    translationTranslate = new TranslateTransform(0, 0);
                    Win.RegisterName(translationTranslate.GetHashCode().ToString(), translationTranslate);
                    tg.Children.Add(translationTranslate);
                    Element.RenderTransform = tg;
                }
            }
            #endregion
            Win.RegisterResource(Story);
            Story = (Storyboard)Story.CloneCurrentValue();
            double danqianX = translation.ScaleX;
            double danqianY = translation.ScaleY;


            Element.RenderTransformOrigin = new Point(0.5, 0.5);
            var keyspline  = new KeySpline(0.55, 0.055, 0.675, 0.19);
            var keyspline2 = new KeySpline(0.175, 0.885, 0.320, 1);

            var k3_0 = new SplineDoubleKeyFrame(1, TimeSpan.FromMilliseconds(AniTime(0)));
            var k3_1 = new SplineDoubleKeyFrame(0.475, TimeSpan.FromMilliseconds(AniTime(0.4)), keyspline2);
            var k3_2 = new SplineDoubleKeyFrame(0.1, TimeSpan.FromMilliseconds(AniTime(1)), keyspline);


            Storyboard.SetTargetName(dauX, Win.GetName(translation));
            Storyboard.SetTargetProperty(dauX, new PropertyPath(ScaleTransform.ScaleXProperty));
            dauX.KeyFrames.Add(k3_0);
            dauX.KeyFrames.Add(k3_1);
            dauX.KeyFrames.Add(k3_2);
            Story.Children.Add(dauX);


            Storyboard.SetTargetName(dauY, Win.GetName(translation));
            Storyboard.SetTargetProperty(dauY, new PropertyPath(ScaleTransform.ScaleYProperty));
            dauY.KeyFrames.Add(k3_0);
            dauY.KeyFrames.Add(k3_1);
            dauY.KeyFrames.Add(k3_2);
            Story.Children.Add(dauY);

            dauX.FillBehavior = FillBehavior.Stop;
            dauY.FillBehavior = FillBehavior.Stop;


            dauTranslateY = new DoubleAnimationUsingKeyFrames();

            var k4_0 = new SplineDoubleKeyFrame(0, TimeSpan.FromMilliseconds(AniTime(0)));
            var k4_1 = new SplineDoubleKeyFrame(-60, TimeSpan.FromMilliseconds(AniTime(0.4)), keyspline2);
            var k4_2 = new SplineDoubleKeyFrame(2000, TimeSpan.FromMilliseconds(AniTime(1)), keyspline);

            Storyboard.SetTargetName(dauTranslateY, Win.GetName(translationTranslate));
            Storyboard.SetTargetProperty(dauTranslateY, new PropertyPath(TranslateTransform.YProperty));

            dauTranslateY.KeyFrames.Add(k4_0);
            dauTranslateY.KeyFrames.Add(k4_1);
            dauTranslateY.KeyFrames.Add(k4_2);
            Story.Children.Add(dauTranslateY);

            dauTranslateY.FillBehavior = FillBehavior.Stop;

            dauOpacty = new DoubleAnimationUsingKeyFrames();
            var k6   = new SplineDoubleKeyFrame(1, TimeSpan.FromMilliseconds(AniTime(0)));
            var k6_1 = new SplineDoubleKeyFrame(1, TimeSpan.FromMilliseconds(AniTime(0.4)), keyspline2);
            var k6_2 = new SplineDoubleKeyFrame(0, TimeSpan.FromMilliseconds(AniTime(1)), keyspline);

            dauOpacty.KeyFrames.Add(k6);
            dauOpacty.KeyFrames.Add(k6_1);
            dauOpacty.KeyFrames.Add(k6_2);
            Storyboard.SetTarget(dauOpacty, Element);
            dauOpacty.FillBehavior = FillBehavior.Stop;
            Storyboard.SetTargetProperty(dauOpacty, new PropertyPath(UIElement.OpacityProperty));
            Story.Children.Add(dauOpacty);
            Story.Completed += Story_Completed;
        }
示例#9
0
        /// <summary>
        /// Действия выполняемые при отрисовке контрола.
        /// </summary>
        /// <param name="drawingContext">Контекст отрисовки.</param>
        protected override void OnRender(DrawingContext drawingContext)
        {
            if (this.Markers == null)
            {
                return;
            }

            var renderSize     = this.RenderSize;
            var document       = this.editor.Document;
            var textView       = this.editor.TextArea.TextView;
            var documentHeight = textView.DocumentHeight;

            foreach (var marker in this.Markers)
            {
                if (!IsVisibleOnAdorner(marker))
                {
                    continue;
                }

                var location      = document.GetLocation(marker.StartOffset);
                var visualTop     = textView.GetVisualTopByDocumentLine(location.Line);
                var renderPos     = visualTop / documentHeight * renderSize.Height;
                var brush         = GetBrush(marker.MarkerColor);
                var isMarkerShown = false;

                if ((marker.MarkerType & TextMarkerType.LineInScrollBar) != 0)
                {
                    drawingContext.DrawRectangle(brush, null, new Rect(3, renderPos - 1, renderSize.Width - 6, 2));
                    isMarkerShown = true;
                }

                if ((marker.MarkerType & TextMarkerType.CircleInScrollBar) != 0)
                {
                    const double radius = 3;
                    drawingContext.DrawEllipse(brush, null, new Point(renderSize.Width / 2, renderPos), radius, radius);
                    isMarkerShown = true;
                }

                if (!isMarkerShown)
                {
                    var translateTransform = new TranslateTransform(6, renderPos);
                    translateTransform.Freeze();
                    drawingContext.PushTransform(translateTransform);

                    if ((marker.MarkerType & TextMarkerType.ScrollBarLeftTriangle) != 0)
                    {
                        var scaleTransform = new ScaleTransform(-1, 1);
                        scaleTransform.Freeze();
                        drawingContext.PushTransform(scaleTransform);
                        drawingContext.DrawGeometry(brush, null, triangleGeometry.Value);
                        drawingContext.Pop();
                    }

                    if ((marker.MarkerType & TextMarkerType.ScrollBarRightTriangle) != 0)
                    {
                        drawingContext.DrawGeometry(brush, null, triangleGeometry.Value);
                    }

                    drawingContext.Pop();
                }
            }
        }
示例#10
0
        bool BoxCollision(Image target, TranslateTransform target_position, double step_x, double step_y, Image target2, TranslateTransform target2_position)
        {
            var  x1 = Canvas.GetLeft(target) + target_position.X + step_x;
            var  y1 = Canvas.GetTop(target) + target_position.Y + step_y;
            Rect r1 = new Rect(x1, y1, target.Width - 1, target.Height - 1);
            var  x2 = Canvas.GetLeft(target2) + target2_position.X;
            var  y2 = Canvas.GetTop(target2) + target2_position.Y;
            Rect r2 = new Rect(x2, y2, target2.Width - 1, target2.Height - 1);

            if (r1.IntersectsWith(r2))
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
示例#11
0
        private static void SetViewportPosition(UIElement element, MapBase parentMap, Location location)
        {
            var viewportPosition = new Point();

            if (parentMap != null && location != null)
            {
                var mapPosition = parentMap.MapTransform.Transform(location, parentMap.Center.Longitude); // nearest to center longitude

                viewportPosition = parentMap.ViewportTransform.Transform(mapPosition);

                if ((bool)element.GetValue(FrameworkElement.UseLayoutRoundingProperty))
                {
                    viewportPosition.X = Math.Round(viewportPosition.X);
                    viewportPosition.Y = Math.Round(viewportPosition.Y);
                }
            }

            var translateTransform = element.RenderTransform as TranslateTransform;

            if (translateTransform == null)
            {
                var transformGroup = element.RenderTransform as TransformGroup;

                if (transformGroup == null)
                {
                    translateTransform = new TranslateTransform();
                    element.RenderTransform = translateTransform;
                }
                else
                {
                    if (transformGroup.Children.Count > 0)
                    {
                        translateTransform = transformGroup.Children[transformGroup.Children.Count - 1] as TranslateTransform;
                    }

                    if (translateTransform == null)
                    {
                        translateTransform = new TranslateTransform();
                        transformGroup.Children.Add(translateTransform);
                    }
                }
            }

            translateTransform.X = viewportPosition.X;
            translateTransform.Y = viewportPosition.Y;
        }
示例#12
0
        public static Storyboard CreateSlideAnimation(AnimationRequest request, FadeSide edge, FadeType fadetype)
        {
            double distance  = 0;
            var    sb        = new Storyboard();
            var    slide     = new DoubleAnimationUsingKeyFrames();
            var    fade      = new DoubleAnimationUsingKeyFrames();
            var    transform = new TranslateTransform();
            var    duration  = request.Duration.Milliseconds;

            var KeyframeTimes = new List <double>()
            {
                0, duration / 6, duration
            };                                                                    // 3 key frames.
            List <double> KeyframeDistance = new List <double>();
            List <double> KeyframeOpacity  = new List <double>();

            Storyboard.SetTarget(slide, transform);
            Storyboard.SetTargetProperty(fade, "Opacity");
            Storyboard.SetTarget(fade, request.Target);
            request.Target.RenderTransform = transform;

            switch (fadetype)
            {
            case FadeType.FadeIn:
                KeyframeOpacity = new List <double>()
                {
                    0, 0.8, 1.0
                };

                switch (edge)
                {
                case FadeSide.Top:
                    distance = -request.Target.ActualHeight;
                    Storyboard.SetTargetProperty(slide, "Y");
                    KeyframeDistance = new List <double>()
                    {
                        distance, distance * 0.5, 0
                    };
                    break;

                case FadeSide.Bottom:
                    distance = request.Target.ActualHeight;
                    Storyboard.SetTargetProperty(slide, "Y");
                    KeyframeDistance = new List <double>()
                    {
                        distance, distance * 0.5, 0
                    };
                    break;

                case FadeSide.Left:
                    distance = -request.Target.ActualWidth;
                    Storyboard.SetTargetProperty(slide, "X");
                    KeyframeDistance = new List <double>()
                    {
                        distance, distance * 0.5, 0
                    };
                    break;

                case FadeSide.Right:
                    distance = request.Target.ActualWidth;
                    Storyboard.SetTargetProperty(slide, "X");
                    KeyframeDistance = new List <double>()
                    {
                        distance, distance * 0.5, 0
                    };
                    break;
                }
                break;

            case FadeType.FadeOut:
                KeyframeOpacity = new List <double>()
                {
                    1.0, 0.6, 0
                };
                switch (edge)
                {
                case FadeSide.Top:
                    distance = -request.Target.ActualHeight;
                    Storyboard.SetTargetProperty(slide, "Y");
                    KeyframeDistance = new List <double>()
                    {
                        0, distance * 0.2, distance
                    };
                    break;

                case FadeSide.Bottom:
                    distance = request.Target.ActualHeight;
                    Storyboard.SetTargetProperty(slide, "Y");
                    KeyframeDistance = new List <double>()
                    {
                        0, distance * 0.2, distance
                    };
                    break;

                case FadeSide.Left:
                    distance = -request.Target.ActualWidth;
                    Storyboard.SetTargetProperty(slide, "X");
                    KeyframeDistance = new List <double>()
                    {
                        0, distance * 0.2, distance
                    };
                    break;

                case FadeSide.Right:
                    distance = request.Target.ActualWidth;
                    Storyboard.SetTargetProperty(slide, "X");
                    KeyframeDistance = new List <double>()
                    {
                        0, distance * 0.2, distance
                    };
                    break;
                }
                break;
            }

            for (int i = 0; i < KeyframeTimes.Count; i++)
            {
                slide.KeyFrames.Add(new EasingDoubleKeyFrame()
                {
                    KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(KeyframeTimes[i])), Value = KeyframeDistance[i]
                });
                fade.KeyFrames.Add(new EasingDoubleKeyFrame()
                {
                    KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(KeyframeTimes[i])), Value = KeyframeOpacity[i]
                });
            }

            sb.Children.Add(slide);
            sb.Children.Add(fade);
            if (request.Completed != null)
            {
                sb.Completed += request.Completed;
            }
            return(sb);
        }
示例#13
0
        private void DoAnimation()
        {
            if (start == finish)
            {
                return;
            }
            PathGeometry pathGeometry = new PathGeometry();
            PathFigure   pathFigure   = new PathFigure();
            Point        startingFrom = start.coord;

            startingFrom.X       -= 20;
            startingFrom.Y       -= 20;
            pathFigure.StartPoint = startingFrom;
            pathFigure.Segments.Add(bezie);
            pathGeometry.Figures.Add(pathFigure);

            NameScope.SetNameScope(this, new NameScope());
            DoubleAnimationUsingPath transX = new DoubleAnimationUsingPath();
            DoubleAnimationUsingPath transY = new DoubleAnimationUsingPath();
            Rectangle aRectangle            = new Rectangle();

            aRectangle.Width  = 40;
            aRectangle.Height = 40;
            aRectangle.Fill   = ballBrush;

            TranslateTransform transform = new TranslateTransform();

            this.RegisterName("Transform", transform);

            aRectangle.RenderTransform = transform;
            mainPanel.Children.Add(aRectangle);
            this.Content = mainPanel;

            transX.PathGeometry = pathGeometry;
            transX.Duration     = TimeSpan.FromSeconds(5);
            transX.Source       = PathAnimationSource.X;
            Storyboard.SetTargetName(transX, "Transform");
            Storyboard.SetTargetProperty(transX, new PropertyPath(TranslateTransform.XProperty));

            transY.PathGeometry = pathGeometry;
            transY.Duration     = TimeSpan.FromSeconds(5);
            transY.Source       = PathAnimationSource.Y;
            Storyboard.SetTargetName(transY, "Transform");
            Storyboard.SetTargetProperty(transY, new PropertyPath(TranslateTransform.YProperty));

            Storyboard storyboard = new Storyboard();

            storyboard.Children.Add(transX);
            storyboard.Children.Add(transY);
            storyboard.Duration = TimeSpan.FromSeconds(7);


            aRectangle.Loaded += delegate(object sender, RoutedEventArgs e)
            {
                storyboard.Begin(this);
            };

            storyboard.Completed += delegate(object sender, EventArgs e)
            {
                pathGeometry.Clear();
                mainPanel.Children.Remove(aRectangle);
            };
        }
示例#14
0
        public void drawdirectpath(System.Windows.Point sp, System.Windows.Point ep)
        {
            this.startpos = sp;
            this.endpos   = ep;
            ep            = relativePoint(ep);
            TranslateTransform ptrans = new TranslateTransform();

            ptrans.X    = -3;
            ptrans.Y    = -3;
            pelS.Fill   = new SolidColorBrush(Colors.Red);
            pelS.Width  = 6;
            pelS.Height = 6;
            pelS.SetValue(Canvas.LeftProperty, sp.X);
            pelS.SetValue(Canvas.TopProperty, sp.Y);
            pelS.RenderTransform = ptrans;
            pelE.Fill            = new SolidColorBrush(Colors.Red);
            pelE.Width           = 6;
            pelE.Height          = 6;
            pelE.SetValue(Canvas.LeftProperty, ep.X);
            pelE.SetValue(Canvas.TopProperty, ep.Y);
            pelE.RenderTransform   = ptrans;
            parrow.Stroke          = new SolidColorBrush(Colors.Red);
            parrow.StrokeThickness = 2;
            GeometryGroup pgeometry = new GeometryGroup();

            /* LineGeometry plinegeometry_up = new LineGeometry();
             * plinegeometry_up.StartPoint = new System.Windows.Point(ep.X, ep.Y);
             * plinegeometry_up.EndPoint = new System.Windows.Point(ep.X, ep.Y);*/

            LineGeometry pline = new LineGeometry();

            pline.StartPoint = sp;
            pline.EndPoint   = ep;

            /* LineGeometry plinegeometry_down = new LineGeometry();
             * plinegeometry_down.StartPoint = new System.Windows.Point(ep.X, ep.Y);
             * plinegeometry_down.EndPoint = new System.Windows.Point(ep.X, ep.Y);*/
            //pgeometry.Children.Add(plinegeometry_up);
            // pgeometry.Children.Add(plinegeometry_down);

            plabel.Text       = properties.roadName;
            plabel.Foreground = new SolidColorBrush(Colors.Blue);
            plabel.Width      = 100;
            plabel.SetValue(Canvas.LeftProperty, (startpos.X + endpos.X) / 2);
            plabel.SetValue(Canvas.TopProperty, (startpos.Y + endpos.Y) / 2);
            TranslateTransform ptranstext = new TranslateTransform();

            ptranstext.X           = -plabel.Width / 2 + 25;
            ptranstext.Y           = -10;
            plabel.RenderTransform = ptranstext;
            plabel.TextAlignment   = TextAlignment.Center;

            /*plabel = new TextBlock();
             * plabel.Text = properties.roadName;
             * plabel.Width = 100;
             * plabel.Background = new SolidColorBrush(Colors.Pink);
             * plabel.SetValue(Canvas.LeftProperty, (startpos.X+endpos.X)/2);
             * plabel.SetValue(Canvas.TopProperty, (startpos.Y + endpos.Y) / 2);
             * plabel.TextAlignment = TextAlignment.Center;
             * this.content.Children.Add(plabel);*/

            pgeometry.Children.Add(pline);

            parrow.Data = pgeometry;
        }
示例#15
0
        private void CreateMove(Image target, Image startingImage, Image endImage, out DoubleAnimation moveAnim, out TranslateTransform tt)
        {
            double currentX = target.TransformToAncestor(Application.Current.MainWindow).Transform(new Point(0, 0)).X
                              - target.RenderTransform.Value.OffsetX;
            double startX = startingImage.TransformToAncestor(Application.Current.MainWindow).Transform(new Point(0, 0)).X;
            double endX   = endImage.TransformToAncestor(Application.Current.MainWindow).Transform(new Point(0, 0)).X;

            if (endImage.Source == null)
            {
                endX -= p1Image.Width / 2;
            }

            moveAnim = new DoubleAnimation()
            {
                From           = startX - currentX,
                To             = endX - currentX,
                Duration       = new Duration(TimeSpan.Parse($"0:0:{MoveSpeed:N2}")),
                EasingFunction = new QuarticEase()
            };
            target.RenderTransformOrigin = new Point(0, 0);
            tt = new TranslateTransform();
            target.RenderTransform = tt;
        }
示例#16
0
        protected override Size ArrangeOverride(Size finalSize)
        {
            if (this.Children == null || this.Children.Count == 0)
            {
                return(finalSize);
            }

            TranslateTransform trans = null;

            double curX = 0;
            double curY = ItemTopMargin;

            double delta = SelectedItemLeftMargin;
            bool   init  = false;

            TimeSpan animationLength = TimeSpan.FromMilliseconds(this.AnimationDuration);

            int index = 0;

            foreach (ListBoxItem child in this.Children)
            {
                child.Arrange(new Rect(0, 0, child.DesiredSize.Width, child.DesiredSize.Height));

                trans = child.RenderTransform as TranslateTransform;

                if (trans == null)
                {
                    child.RenderTransformOrigin = new Point(0, 0);
                    trans = new TranslateTransform();
                    child.RenderTransform = trans;

                    double toX = curX + delta - (this.SelectedIndex * child.ActualWidth);
                    trans.X = toX;
                    trans.Y = curY - VerticalOffset;

                    trans.BeginAnimation(TranslateTransform.XProperty,
                                         new DoubleAnimation(toX, animationLength),
                                         HandoffBehavior.Compose);
                    trans.BeginAnimation(TranslateTransform.YProperty,
                                         new DoubleAnimation(curY - VerticalOffset, animationLength),
                                         HandoffBehavior.Compose);

                    init = true;
                }
                else
                {
                    //if (this.elementTimelineDictionary.ContainsKey(child))
                    //{
                    //    DoubleAnimationUsingKeyFrames frames = this.elementTimelineDictionary[child] as DoubleAnimationUsingKeyFrames;
                    //    trans.X = frames.KeyFrames[frames.KeyFrames.Count - 1].Value;
                    //    //     frames.SpeedRatio = 100;

                    //    //     Thread.Sleep(1);

                    //    //     trans.BeginAnimation(TranslateTransform.YProperty, null, HandoffBehavior.Compose);
                    //}
                }

                curX            += child.DesiredSize.Width;
                finalSize.Height = child.DesiredSize.Height;
            }

            if (init)
            {
                return(finalSize);
            }

            UIElement selectedItem = this.SelectedItem;

            if (selectedItem != null)
            {
                TranslateTransform selectedItemTrans = selectedItem.RenderTransform as TranslateTransform;
                delta = SelectedItemLeftMargin - selectedItemTrans.X;
                if (this.elementTimelineDictionary.ContainsKey(selectedItem))
                {
                    if (this.elementTimelineDictionary[selectedItem] is DoubleAnimationUsingKeyFrames)
                    {
                        DoubleAnimationUsingKeyFrames frames = this.elementTimelineDictionary[selectedItem] as DoubleAnimationUsingKeyFrames;
                        if (frames.KeyFrames.Count > 0)
                        {
                            delta = SelectedItemLeftMargin - frames.KeyFrames[frames.KeyFrames.Count - 1].Value;
                        }
                    }
                    else
                    {
                        DoubleAnimation doubleAnimation = this.elementTimelineDictionary[selectedItem] as DoubleAnimation;
                        if (doubleAnimation != null)
                        {
                            delta = SelectedItemLeftMargin - doubleAnimation.To.Value;
                        }
                    }
                }
            }

            if (delta == 0)
            {
                return(finalSize);
            }

            index = 0;
            if (this.CircleItems)
            {
                double             lastRight = this.SpaceAfterLastItem;
                TranslateTransform lastTrans = this.Children[this.Children.Count - 1].RenderTransform as TranslateTransform;
                lastRight = lastTrans.X + this.Children[this.Children.Count - 1].DesiredSize.Width;

                if (this.elementTimelineDictionary.ContainsKey(this.Children[this.Children.Count - 1]))
                {
                    DoubleAnimationUsingKeyFrames frames = this.elementTimelineDictionary[this.Children[this.Children.Count - 1]] as DoubleAnimationUsingKeyFrames;
                    if (frames.KeyFrames.Count > 0)
                    {
                        lastRight = frames.KeyFrames[frames.KeyFrames.Count - 1].Value + this.Children[this.Children.Count - 1].DesiredSize.Width;
                    }
                }

                double             firstLeft  = this.SelectedItemLeftMargin;
                TranslateTransform firstTrans = this.Children[0].RenderTransform as TranslateTransform;
                firstLeft = firstTrans.X;

                if (this.elementTimelineDictionary.ContainsKey(this.Children[0]))
                {
                    DoubleAnimationUsingKeyFrames frames = this.elementTimelineDictionary[this.Children[0]] as DoubleAnimationUsingKeyFrames;
                    if (frames.KeyFrames.Count > 0)
                    {
                        firstLeft = frames.KeyFrames[frames.KeyFrames.Count - 1].Value;
                    }
                }

                double startX = lastRight + this.SpaceAfterLastItem;
                double endX   = firstLeft - this.SpaceAfterLastItem;

                if (delta < 0) // forward
                {
                    foreach (UIElement child in this.Children)
                    {
                        trans = child.RenderTransform as TranslateTransform;

                        double fromX = trans.X;
                        Debug.WriteLine(string.Format("Start fromX left {0}", fromX));
                        if (this.elementTimelineDictionary.ContainsKey(child))
                        {
                            DoubleAnimationUsingKeyFrames frames = this.elementTimelineDictionary[child] as DoubleAnimationUsingKeyFrames;
                            fromX = frames.KeyFrames[frames.KeyFrames.Count - 1].Value;

                            Debug.WriteLine(string.Format("End fromX left {0}", fromX));
                        }

                        double toX = fromX + delta;

                        DoubleAnimationUsingKeyFrames doubleAnimationUsingKeyFrames = new DoubleAnimationUsingKeyFrames();
                        doubleAnimationUsingKeyFrames.Duration       = new Duration(animationLength + TimeSpan.FromMilliseconds(index * 10));
                        doubleAnimationUsingKeyFrames.RepeatBehavior = new RepeatBehavior(1);
                        doubleAnimationUsingKeyFrames.AutoReverse    = false;
                        doubleAnimationUsingKeyFrames.FillBehavior   = FillBehavior.HoldEnd;

                        if (child == this.SelectedItem)
                        {
                            doubleAnimationUsingKeyFrames.Completed += new EventHandler(doubleAnimationUsingKeyFrames_Completed);
                        }

                        if (!this.elementTimelineDictionary.ContainsKey(child))
                        {
                            this.elementTimelineDictionary.Add(child, doubleAnimationUsingKeyFrames);
                        }
                        else
                        {
                            this.elementTimelineDictionary[child] = doubleAnimationUsingKeyFrames;
                        }

                        LinearDoubleKeyFrame frame1 = new LinearDoubleKeyFrame();
                        frame1.Value = toX;
                        doubleAnimationUsingKeyFrames.KeyFrames.Add(frame1);

                        if (fromX > lastRight)
                        {
                            startX += child.DesiredSize.Width;
                        }

                        if (toX + child.DesiredSize.Width <= 0) // Move item to end
                        {
                            double fromBK = fromX;
                            if (fromX > lastRight)
                            {
                                startX -= child.DesiredSize.Width;
                            }

                            fromX   = startX;
                            toX     = startX + delta;
                            startX += child.DesiredSize.Width;

                            DiscreteDoubleKeyFrame frame2 = new DiscreteDoubleKeyFrame();
                            frame2.Value = fromX;
                            doubleAnimationUsingKeyFrames.KeyFrames.Add(frame2);

                            LinearDoubleKeyFrame frame3 = new LinearDoubleKeyFrame();
                            frame3.Value = toX;
                            doubleAnimationUsingKeyFrames.KeyFrames.Add(frame3);
                        }

                        if (doubleAnimationUsingKeyFrames.KeyFrames.Count == 3)
                        {
                            doubleAnimationUsingKeyFrames.KeyFrames[0].KeyTime = KeyTime.FromPercent(0.5);
                            doubleAnimationUsingKeyFrames.KeyFrames[1].KeyTime = KeyTime.FromPercent(0.5);
                            doubleAnimationUsingKeyFrames.KeyFrames[2].KeyTime = KeyTime.FromPercent(1.0);
                        }
                        else
                        {
                            doubleAnimationUsingKeyFrames.KeyFrames[0].KeyTime = KeyTime.FromPercent(1.0);
                        }

                        trans.BeginAnimation(TranslateTransform.XProperty,
                                             doubleAnimationUsingKeyFrames,
                                             HandoffBehavior.Compose);
                        trans.BeginAnimation(TranslateTransform.YProperty,
                                             new DoubleAnimation(curY - VerticalOffset, animationLength),
                                             HandoffBehavior.Compose);

                        index++;
                    }
                }
                else
                {
                    index = this.Children.Count;
                    for (int i = this.Children.Count - 1; i >= 0; i--)
                    {
                        UIElement child = this.Children[i];

                        trans = child.RenderTransform as TranslateTransform;

                        double fromX = trans.X;
                        if (this.elementTimelineDictionary.ContainsKey(child))
                        {
                            DoubleAnimationUsingKeyFrames frames = this.elementTimelineDictionary[child] as DoubleAnimationUsingKeyFrames;
                            fromX = frames.KeyFrames[frames.KeyFrames.Count - 1].Value;
                        }

                        double toX = fromX + delta;

                        DoubleAnimationUsingKeyFrames doubleAnimationUsingKeyFrames = new DoubleAnimationUsingKeyFrames();
                        doubleAnimationUsingKeyFrames.Duration       = new Duration(animationLength + TimeSpan.FromMilliseconds(index * 10));
                        doubleAnimationUsingKeyFrames.RepeatBehavior = new RepeatBehavior(1);
                        doubleAnimationUsingKeyFrames.AutoReverse    = false;
                        doubleAnimationUsingKeyFrames.FillBehavior   = FillBehavior.HoldEnd;

                        if (i == this.SelectedIndex)
                        {
                            doubleAnimationUsingKeyFrames.Completed += new EventHandler(doubleAnimationUsingKeyFrames_Completed);
                        }

                        if (!this.elementTimelineDictionary.ContainsKey(child))
                        {
                            this.elementTimelineDictionary.Add(child, doubleAnimationUsingKeyFrames);
                        }
                        else
                        {
                            this.elementTimelineDictionary[child] = doubleAnimationUsingKeyFrames;
                        }

                        LinearDoubleKeyFrame frame1 = new LinearDoubleKeyFrame();
                        frame1.Value = toX;
                        doubleAnimationUsingKeyFrames.KeyFrames.Add(frame1);

                        if (fromX < firstLeft)
                        {
                            endX -= child.DesiredSize.Width;
                        }

                        if (toX > finalSize.Width) // Move item to front
                        {
                            double fromBK = fromX;
                            if (fromX < firstLeft)
                            {
                                endX += child.DesiredSize.Width;
                            }

                            fromX = endX - delta;
                            toX   = endX;
                            endX -= child.DesiredSize.Width;

                            DiscreteDoubleKeyFrame frame2 = new DiscreteDoubleKeyFrame();
                            frame2.Value = fromX;
                            doubleAnimationUsingKeyFrames.KeyFrames.Add(frame2);

                            LinearDoubleKeyFrame frame3 = new LinearDoubleKeyFrame();
                            frame3.Value = toX;
                            doubleAnimationUsingKeyFrames.KeyFrames.Add(frame3);
                        }

                        if (doubleAnimationUsingKeyFrames.KeyFrames.Count == 3)
                        {
                            doubleAnimationUsingKeyFrames.KeyFrames[0].KeyTime = KeyTime.FromPercent(0.5);
                            doubleAnimationUsingKeyFrames.KeyFrames[1].KeyTime = KeyTime.FromPercent(0.5);
                            doubleAnimationUsingKeyFrames.KeyFrames[2].KeyTime = KeyTime.FromPercent(1.0);
                        }
                        else
                        {
                            doubleAnimationUsingKeyFrames.KeyFrames[0].KeyTime = KeyTime.FromPercent(1.0);
                        }

                        trans.BeginAnimation(TranslateTransform.XProperty,
                                             doubleAnimationUsingKeyFrames,
                                             HandoffBehavior.Compose);
                        trans.BeginAnimation(TranslateTransform.YProperty,
                                             new DoubleAnimation(curY - VerticalOffset, animationLength),
                                             HandoffBehavior.Compose);

                        index--;
                    }
                }
            }
            else
            {
                foreach (UIElement child in this.Children)
                {
                    trans = child.RenderTransform as TranslateTransform;

                    double fromX = trans.X;
                    if (this.elementTimelineDictionary.ContainsKey(child))
                    {
                        DoubleAnimation old = this.elementTimelineDictionary[child] as DoubleAnimation;
                        fromX = old.To.Value;
                    }
                    double toX = fromX + delta;

                    DoubleAnimation doubleAnimation = new DoubleAnimation();
                    doubleAnimation.From     = fromX;
                    doubleAnimation.To       = toX;
                    doubleAnimation.Duration = animationLength;

                    trans.BeginAnimation(TranslateTransform.XProperty,
                                         doubleAnimation,
                                         HandoffBehavior.Compose);
                    trans.BeginAnimation(TranslateTransform.YProperty,
                                         new DoubleAnimation(curY - VerticalOffset, animationLength),
                                         HandoffBehavior.Compose);

                    if (!this.elementTimelineDictionary.ContainsKey(child))
                    {
                        this.elementTimelineDictionary.Add(child, doubleAnimation);
                    }
                    else
                    {
                        this.elementTimelineDictionary[child] = doubleAnimation;
                    }

                    index++;
                }
            }

            return(finalSize);
        }
示例#17
0
        public void MoveMessage()
        {
            // フォントサイズの決定
            double fontsize = 100;

            foreach (string sizeName in fontSizeMap.Keys)
            {
                if (message.Contains(sizeName))
                {
                    message  = message.Remove(message.IndexOf(sizeName), sizeName.Length);
                    fontsize = fontSizeMap[sizeName];
                }
            }
            // フォントカラーの決定
            Brush fontcolor = Brushes.White;

            //Console.WriteLine(color);

            foreach (string colorname in fontColorMap.Keys)
            {
                if (colorname == color)
                {
                    fontcolor = fontColorMap[colorname];
                }
            }
            // 新しいテキストを生成
            TextBlock textBlock = new TextBlock();

            textBlock.FontSize   = fontsize;
            textBlock.Text       = message.Trim();
            textBlock.Foreground = fontcolor;
            canvas.Children.Add(textBlock);
            // テキストに影をつける
            DropShadowBitmapEffect effect = new DropShadowBitmapEffect();

            effect.ShadowDepth     = 4;
            effect.Direction       = 330;
            effect.Color           = (Color)ColorConverter.ConvertFromString("black");
            textBlock.BitmapEffect = effect;
            // 文字サイズに合わせてテキストの位置を指定
            verticalPosition += (int)fontsize;
            if (verticalPosition >= this.Height)
            {
                verticalPosition = 0;
            }
            TranslateTransform transform = new TranslateTransform(this.Width, this.Height);

            // テキストのアニメーション
            textBlock.RenderTransform = transform;
            Duration duration;

            //文字数によって流す速さを変更
            if (message.Length < 10)
            {
                duration = new Duration(TimeSpan.FromMilliseconds(5000));
            }
            else if (message.Length > 30)
            {
                duration = new Duration(TimeSpan.FromMilliseconds(20000));
            }
            else
            {
                duration = new Duration(TimeSpan.FromMilliseconds(message.Length * 500));
            }

            //アニメーションを使用して右から左に流す(横方向のためX座標)
            DoubleAnimation animationX = new DoubleAnimation(-1 * message.Length * fontsize, duration);

            transform.BeginAnimation(TranslateTransform.XProperty, animationX);
        }
示例#18
0
        private void ReconstructGrid()
        {
            _cells = new Rectangle[_map.Width, _map.Height];
            MainCanvas.Children.Clear();
            CalculateFitTransform();

            // Create transform objects
            _fixedRenderTransform    = new TransformGroup();
            _fixedTranslateTransform = new TranslateTransform(_fixedOffsetX, _fixedOffsetY);
            _fixedScaleTransform     = new ScaleTransform(_fixedScale, _fixedScale, 0, 0);
            _fixedRenderTransform.Children.Add(_fixedScaleTransform);
            _fixedRenderTransform.Children.Add(_fixedTranslateTransform);

            _renderTransform    = new TransformGroup();
            _translateTransform = new TranslateTransform();
            _scaleTransform     = new ScaleTransform();
            _renderTransform.Children.Add(_scaleTransform);
            _renderTransform.Children.Add(_translateTransform);

            _fixedRenderTransform.Children.Add(_renderTransform);

            // Generate cells
            for (int i = 0; i < _map.Width; ++i)
            {
                for (int j = 0; j < _map.Height; ++j)
                {
                    Rectangle      cell          = new Rectangle();
                    TransformGroup cellTransform = new TransformGroup();
                    cellTransform.Children.Add(new TranslateTransform(10 * i, 10 * j));
                    cellTransform.Children.Add(_fixedRenderTransform);
                    cell.RenderTransform       = cellTransform;
                    cell.Width                 = 10;
                    cell.Height                = 10;
                    cell.Fill                  = new SolidColorBrush(_status[_map[i, j]].DisplayColor);
                    cell.Name                  = "_" + j + "_" + i + "_";
                    cell.MouseRightButtonDown += Cell_OnMouseRightButtonDown;
                    //cell.MouseMove += MainCanvas_OnMouseMove;
                    MainCanvas.Children.Add(cell);
                    _cells[i, j] = cell;
                }
            }

            // Draw grid
            for (int i = 0; i <= _map.Width; ++i)
            {
                Line line = new Line();
                line.RenderTransformOrigin = new Point(0, 0);
                line.RenderTransform       = _fixedRenderTransform;
                line.X1 = 10 * i;
                line.X2 = 10 * i;
                line.Y1 = 0;
                line.Y2 = 10 * _map.Height;
                line.StrokeThickness = 0.5;
                line.Stroke          = Brushes.Gray;
                MainCanvas.Children.Add(line);
            }

            for (int i = 0; i <= _map.Height; ++i)
            {
                Line line = new Line();
                line.RenderTransformOrigin = new Point(0, 0);
                line.RenderTransform       = _fixedRenderTransform;
                line.X1 = 0;
                line.X2 = 10 * _map.Width;
                line.Y1 = 10 * i;
                line.Y2 = 10 * i;
                line.StrokeThickness = 0.5;
                line.Stroke          = Brushes.Gray;
                MainCanvas.Children.Add(line);
            }
        }
示例#19
0
        private static void SetViewportPosition(UIElement element, MapBase parentMap, Location location)
        {
            Point viewportPosition;

            if (parentMap != null && location != null)
            {
                var mapPosition = parentMap.MapTransform.Transform(location, parentMap.Center.Longitude); // nearest to center longitude
                viewportPosition = parentMap.ViewportTransform.Transform(mapPosition);
                element.SetValue(ViewportPositionProperty, viewportPosition);
            }
            else
            {
                viewportPosition = new Point();
                element.ClearValue(ViewportPositionProperty);
            }

            var translateTransform = element.RenderTransform as TranslateTransform;

            if (translateTransform == null)
            {
                var transformGroup = element.RenderTransform as TransformGroup;

                if (transformGroup == null)
                {
                    translateTransform = new TranslateTransform();
                    element.RenderTransform = translateTransform;
                }
                else
                {
                    if (transformGroup.Children.Count > 0)
                    {
                        translateTransform = transformGroup.Children[transformGroup.Children.Count - 1] as TranslateTransform;
                    }

                    if (translateTransform == null)
                    {
                        translateTransform = new TranslateTransform();
                        transformGroup.Children.Add(translateTransform);
                    }
                }
            }

            translateTransform.X = viewportPosition.X;
            translateTransform.Y = viewportPosition.Y;
        }
示例#20
0
        // Should slide these in from the left and right
        private void showNewImages()
        {
            double delayBuildUp = 0;

            for (int i = 0; i < mainHolder.Children.Count; i++)
            {
                // need to get references to each border
                var curBorder = mainHolder.Children[i] as Border;
                if (curBorder != null)
                {
                    // Figure out a random placement and tilted angle on the display
                    // -45 to 45
                    int angle = _rand.Next(-10, 10);

                    // We know that the scroller needs 200 px
                    // We know the actual bar needs 74
                    double availableWidth  = GlobalConfiguration.currentScreenW - 640 - 50;
                    int    finX            = _rand.Next(50, (int)availableWidth);
                    double availableHeight = GlobalConfiguration.currentScreenH - 250 - 480;
                    int    finY            = _rand.Next(0, (int)availableHeight);

                    var previousPoints = (Point)curBorder.GetValue(FrameworkElement.TagProperty);
                    if (previousPoints != null)
                    {
                        // Transforms for moving and rotating - need the first positions
                        TranslateTransform moveTransform   = new TranslateTransform(previousPoints.X, previousPoints.Y);
                        RotateTransform    rotTransform    = new RotateTransform(0);
                        TransformGroup     photoTransforms = new TransformGroup();
                        photoTransforms.Children.Add(moveTransform);
                        photoTransforms.Children.Add(rotTransform);

                        curBorder.RenderTransform = photoTransforms;

                        SineEase ease = new SineEase();
                        ease.EasingMode = EasingMode.EaseOut;

                        DoubleAnimation daMoveX  = new DoubleAnimation();
                        DoubleAnimation daMoveY  = new DoubleAnimation();
                        DoubleAnimation daRotate = new DoubleAnimation();
                        daMoveX.To              = finX;
                        daMoveY.To              = finY;
                        daRotate.To             = angle;
                        daMoveX.EasingFunction  = ease;
                        daRotate.EasingFunction = ease;
                        daMoveY.EasingFunction  = ease;

                        int moveRandTime = _rand.Next(1, 3);
                        daMoveX.Duration  = TimeSpan.FromSeconds(moveRandTime);
                        daRotate.Duration = TimeSpan.FromSeconds(_rand.Next(1, 2));
                        daMoveY.Duration  = TimeSpan.FromSeconds(moveRandTime);

                        daMoveX.BeginTime  = TimeSpan.FromSeconds(delayBuildUp);
                        daMoveY.BeginTime  = TimeSpan.FromSeconds(delayBuildUp);
                        daRotate.BeginTime = TimeSpan.FromSeconds(delayBuildUp);
                        delayBuildUp      += .3;

                        // Only add a complete listener to the final guy
                        if (i == mainHolder.Children.Count - 1)
                        {
                            daMoveX.Completed += handleAnimationOnComplete;
                        }

                        moveTransform.BeginAnimation(TranslateTransform.XProperty, daMoveX);
                        moveTransform.BeginAnimation(TranslateTransform.YProperty, daMoveY);
                        rotTransform.BeginAnimation(RotateTransform.AngleProperty, daRotate);
                    }
                }
            }
        }
示例#21
0
        private void PraiseAnimation()
        {
            var story = new Storyboard();

            //随机选择一张图片
            Random      random      = new Random((int)DateTime.Now.Ticks);
            int         index       = random.Next(3);
            var         uri         = new Uri(images[index]);
            BitmapImage bitmapImage = new BitmapImage(uri);
            var         image       = new Image()
            {
                Source = bitmapImage, Stretch = Stretch.Uniform, Width = 30, Height = 30, Opacity = 0
            };
            var transform = new TranslateTransform();

            image.RenderTransform = transform;

            //随机选择一个动画路径
            int          geometryIndex = random.Next(pathGeometries.Count);
            PathGeometry path          = pathGeometries[geometryIndex];

            var animation1 = new DoubleAnimationUsingPath()
            {
                Duration     = new TimeSpan(0, 0, 5),
                Source       = PathAnimationSource.X,
                PathGeometry = path,
                AutoReverse  = false,
            };

            Storyboard.SetTarget(animation1, image);
            Storyboard.SetTargetProperty(animation1, new PropertyPath("RenderTransform.X"));
            story.Children.Add(animation1);

            var animation2 = new DoubleAnimationUsingPath()
            {
                Duration     = new TimeSpan(0, 0, 5),
                Source       = PathAnimationSource.Y,
                PathGeometry = path,
                AutoReverse  = false,
            };

            Storyboard.SetTarget(animation2, image);
            Storyboard.SetTargetProperty(animation2, new PropertyPath("RenderTransform.Y"));
            story.Children.Add(animation2);

            var animation3 = new DoubleAnimation()
            {
                Duration    = new TimeSpan(0, 0, 5),
                From        = 1,
                To          = 0,
                AutoReverse = false,
            };

            Storyboard.SetTarget(animation3, image);
            Storyboard.SetTargetProperty(animation3, new PropertyPath(Image.OpacityProperty));
            story.Children.Add(animation3);

            paint.Children.Add(image);

            //动画完成后将图片从UI中移除
            story.Completed += new EventHandler((o, e) =>
            {
                paint.Dispatcher.Invoke(() =>
                {
                    paint.Children.Remove(image);
                });
            });

            //开始动画
            story.Begin(image);
        }
			static bool PrepareControlForTilt(FrameworkElement element, Point centerDelta)
#endif
		{
			// Prevents interference with any existing transforms
			if (element.Projection != null || (element.RenderTransform != null && element.RenderTransform.GetType() != typeof(MatrixTransform)))
			{
				return false;
			}

			OriginalCacheMode[element] = element.CacheMode;
			element.CacheMode = new BitmapCache();

			var transform = new TranslateTransform {X = centerDelta.X, Y = centerDelta.Y};
			element.RenderTransform = transform;

			var projection = new PlaneProjection {GlobalOffsetX = -1*centerDelta.X, GlobalOffsetY = -1*centerDelta.Y};
			element.Projection = projection;

#if WINDOWS_STORE
			element.PointerMoved += TiltEffect_PointerMoved;
			element.PointerReleased += TiltEffect_PointerReleased;
			element.PointerCaptureLost += TiltEffect_PointerCaptureLost;
			element.CapturePointer(p);
#elif WINDOWS_PHONE
			element.ManipulationDelta += TiltEffectDelta;
			element.ManipulationCompleted += TiltEffectCompleted;
#endif
			return true;
		}
示例#23
0
        public override void Plot(bool animate = true)
        {
            var chart = Chart as IBar;

            if (chart == null)
            {
                return;
            }
            var barSeries = Chart.Series.OfType <BarSeries>().ToList();
            var pos       = barSeries.IndexOf(this);
            var count     = barSeries.Count;
            var unitW     = ToPlotArea(1, AxisTags.X) - Chart.PlotArea.X + 5;
            var overflow  = unitW - chart.MaxColumnWidth * 3 > 0 ? unitW - chart.MaxColumnWidth * 3 : 0;

            unitW = unitW > chart.MaxColumnWidth * 3 ? chart.MaxColumnWidth * 3 : unitW;

            var       pointPadding  = .1 * unitW;
            const int seriesPadding = 2;
            var       barW          = (unitW - 2 * pointPadding) / count;

            foreach (var point in ChartPoints)
            {
                var t = new TranslateTransform();
                var r = new Rectangle
                {
                    StrokeThickness = StrokeThickness,
                    Stroke          = Stroke,
                    Fill            = Fill,
                    Width           = Math.Max(0, barW - seriesPadding),
                    Height          = 0,
                    RenderTransform = t
                };
                var rh = ToPlotArea(Chart.Min.Y, AxisTags.Y) - ToPlotArea(point.Y, AxisTags.Y);
                var hr = new Rectangle
                {
                    Fill            = Brushes.Transparent,
                    StrokeThickness = 0,
                    Width           = Width = Math.Max(0, barW - seriesPadding),
                    Height          = rh
                };

                Canvas.SetLeft(r, ToPlotArea(point.X, AxisTags.X) + barW * pos + pointPadding + overflow / 2);
                Canvas.SetLeft(hr, ToPlotArea(point.X, AxisTags.X) + barW * pos + pointPadding + overflow / 2);
                Canvas.SetTop(hr, ToPlotArea(Chart.Min.Y, AxisTags.Y) - rh);
                Panel.SetZIndex(hr, int.MaxValue);

                Chart.Canvas.Children.Add(r);
                Chart.Canvas.Children.Add(hr);
                Shapes.Add(r);
                Shapes.Add(hr);

                var hAnim = new DoubleAnimation
                {
                    To       = rh,
                    Duration = TimeSpan.FromMilliseconds(300)
                };
                var rAnim = new DoubleAnimation
                {
                    From     = ToPlotArea(Chart.Min.Y, AxisTags.Y),
                    To       = ToPlotArea(Chart.Min.Y, AxisTags.Y) - rh,
                    Duration = TimeSpan.FromMilliseconds(300)
                };

                var animated = false;
                if (!Chart.DisableAnimation)
                {
                    if (animate)
                    {
                        r.BeginAnimation(HeightProperty, hAnim);
                        t.BeginAnimation(TranslateTransform.YProperty, rAnim);
                        animated = true;
                    }
                }

                if (!animated)
                {
                    r.Height = rh;
                    t.Y      = ToPlotArea(Chart.Min.Y, AxisTags.Y) - rh;
                }

                if (!Chart.Hoverable)
                {
                    continue;
                }
                hr.MouseEnter += Chart.DataMouseEnter;
                hr.MouseLeave += Chart.DataMouseLeave;
                Chart.HoverableShapes.Add(new HoverableShape
                {
                    Series = this,
                    Shape  = hr,
                    Target = r,
                    Value  = point
                });
            }
        }
 static async Task SetBackgroundImageBytesAsync(byte[] imageBytes, Panel control, PositionLength horizontal, PositionLength vertical)
 {
     var bmpImage = await ByteArrayToImageAsync(imageBytes);
     var imageBrush = new ImageBrush() { ImageSource = bmpImage, Stretch = Stretch.None };
     if (horizontal != null)
     {
         switch (horizontal.Unit)
         {
             case PositionLengthUnit.CenterAlign:
                 imageBrush.AlignmentX = AlignmentX.Center;
                 break;
             case PositionLengthUnit.NearAlign:
                 imageBrush.AlignmentX = AlignmentX.Left;
                 break;
             case PositionLengthUnit.FarAlign:
                 imageBrush.AlignmentX = AlignmentX.Right;
                 break;
             case PositionLengthUnit.Absolute:
                 imageBrush.AlignmentX = AlignmentX.Left;
                 imageBrush.Transform = new TranslateTransform() { X = horizontal.Value };
                 break;
             case PositionLengthUnit.Percentage:
                 imageBrush.AlignmentX = AlignmentX.Left;
                 imageBrush.RelativeTransform = new TranslateTransform() { X = horizontal.Value };
                 break;
         }
     }
     if (vertical != null)
     {
         switch (vertical.Unit)
         {
             case PositionLengthUnit.CenterAlign:
                 imageBrush.AlignmentY = AlignmentY.Center;
                 break;
             case PositionLengthUnit.NearAlign:
                 imageBrush.AlignmentY = AlignmentY.Top;
                 break;
             case PositionLengthUnit.FarAlign:
                 imageBrush.AlignmentY = AlignmentY.Bottom;
                 break;
             case PositionLengthUnit.Absolute:
                 imageBrush.AlignmentY = AlignmentY.Top;
                 var transform = imageBrush.Transform as TranslateTransform;
                 if (transform == null)
                 {
                     transform = new TranslateTransform();
                     imageBrush.Transform = transform;
                 }
                 transform.Y = vertical.Value;
                 break;
             case PositionLengthUnit.Percentage:
                 imageBrush.AlignmentY = AlignmentY.Top;
                 var relativeTransform = imageBrush.RelativeTransform as TranslateTransform;
                 if (relativeTransform == null)
                 {
                     relativeTransform = new TranslateTransform();
                     imageBrush.RelativeTransform = relativeTransform;
                 }
                 relativeTransform.Y = vertical.Value;
                 break;
         }
     }
     control.Background = imageBrush;
 }
示例#25
0
        private void dragInterceptor_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
        {
            if (this.Items.Count <= 1 || this.dragItem == null)
            {
                return;
            }
            e.Handled = true;
            if (this.dropTargetIndex == -1)
            {
                if (this.dragItemContainer == null)
                {
                    return;
                }
                Size            renderSize      = this.dragItemContainer.RenderSize;
                WriteableBitmap writeableBitmap = new WriteableBitmap((int)renderSize.Width, (int)renderSize.Height);
                VisualStateManager.GoToState((Control)this.dragItemContainer, "NotDragging", false);
                VisualStateManager.GoToState((Control)this.dragItemContainer, "Dragging", false);
                writeableBitmap.Render((UIElement)this.dragItemContainer, (Transform)null);
                writeableBitmap.Invalidate();
                this.dragIndicator.Source         = (ImageSource)writeableBitmap;
                this.dragIndicator.Visibility     = Visibility.Visible;
                this.dragItemContainer.Visibility = Visibility.Collapsed;
                if (this.itemsPanel.Children.IndexOf((UIElement)this.dragItemContainer) < this.itemsPanel.Children.Count - 2)
                {
                    this.UpdateDropTarget(Canvas.GetTop((UIElement)this.dragIndicator) + this.dragIndicator.Height + 1.0, false);
                }
                else
                {
                    this.UpdateDropTarget(Canvas.GetTop((UIElement)this.dragIndicator) - 1.0, false);
                }
            }
            double             height             = this.dragIndicator.Height;
            TranslateTransform translateTransform = (TranslateTransform)this.dragIndicator.RenderTransform;
            double             top  = Canvas.GetTop((UIElement)this.dragIndicator);
            double             num1 = top + e.CumulativeManipulation.Translation.Y;

            if (num1 < 0.0)
            {
                num1 = 0.0;
                this.UpdateDropTarget(0.0, true);
            }
            else if (num1 >= this.dragInterceptorRect.Height - height)
            {
                num1 = this.dragInterceptorRect.Height - height;
                this.UpdateDropTarget(this.dragInterceptorRect.Height - 1.0, true);
            }
            else
            {
                this.UpdateDropTarget(num1 + height / 2.0, true);
            }
            double num2 = num1 - top;

            translateTransform.Y = num2;
            bool   flag             = this.dragScrollDelta != 0.0;
            double autoScrollMargin = this.AutoScrollMargin;

            if (autoScrollMargin > 0.0 && num1 < autoScrollMargin)
            {
                this.dragScrollDelta = num1 - autoScrollMargin;
                if (flag)
                {
                    return;
                }
                VisualStateManager.GoToState((Control)this.scrollViewer, "Scrolling", true);
                this.Dispatcher.BeginInvoke((Action)(() => this.DragScroll()));
            }
            else if (autoScrollMargin > 0.0 && num1 + height > this.dragInterceptorRect.Height - autoScrollMargin)
            {
                this.dragScrollDelta = num1 + height - (this.dragInterceptorRect.Height - autoScrollMargin);
                if (flag)
                {
                    return;
                }
                VisualStateManager.GoToState((Control)this.scrollViewer, "Scrolling", true);
                this.Dispatcher.BeginInvoke((Action)(() => this.DragScroll()));
            }
            else
            {
                this.dragScrollDelta = 0.0;
            }
        }
        private void moveIn(object sender, EventArgs e)
        {
            Int32 pageSwitchType = dPage.pageSwitchType;

            if (isBack && backPageSwitchType > 0)
            {
                pageSwitchType = backPageSwitchType;
            }
            if (pageSwitchType <= 0)
            {
                pageSwitchType = 1;
            }
            int pageWidth = dPage.width;

            if (pageWidth <= 0)
            {
                pageWidth = App.localStorage.cfg.screenWidth;
            }


            //1.默认
            if (pageSwitchType == 1)
            {
                mainFrame.Background = Brushes.Transparent;
                return;
            }
            //2.淡入
            else if (pageSwitchType == 2)
            {
                TransformGroup group = new TransformGroup();
                RenderTransform = group;
                DoubleAnimation da = new DoubleAnimation(0, 1.0, new Duration(TimeSpan.FromMilliseconds(400)));
                da.BeginTime = TimeSpan.FromMilliseconds(0);
                IEasingFunction easingFunction = new SineEase()
                {
                    EasingMode = EasingMode.EaseOut
                };
                da.EasingFunction = easingFunction;
                da.Completed     += a2_Completed;
                BeginAnimation(UIElement.OpacityProperty, da);
                return;
            }

            //3.右侧移入
            else if (pageSwitchType == 3)
            {
                if (isBack)
                {
                    return;
                }



                TransformGroup group = new TransformGroup();
                RenderTransform = group;

                double             middlePos          = pageWidth / 2;
                TranslateTransform translateTransform = TransformGroupUtil.GetTranslateTransform(group);
                DoubleAnimation    da = new DoubleAnimation(middlePos, 0, new Duration(TimeSpan.FromMilliseconds(500)));
                da.BeginTime = TimeSpan.FromMilliseconds(0);
                IEasingFunction easingFunction = new SineEase()
                {
                    EasingMode = EasingMode.EaseOut
                };
                da.AccelerationRatio = 0.9;
                //  da.EasingFunction = easingFunction;
                da.Completed += a2_Completed;
                translateTransform.BeginAnimation(TranslateTransform.XProperty, da);


                Opacity = 0;
                DoubleAnimation da1 = new DoubleAnimation(0, 1.0, new Duration(TimeSpan.FromMilliseconds(100)));
                da1.BeginTime      = TimeSpan.FromMilliseconds(0);
                da1.EasingFunction = easingFunction;
                BeginAnimation(UIElement.OpacityProperty, da1);
                return;
            }

            //4.右侧拉伸
            else if (pageSwitchType == 4)
            {
                if (isBack)
                {
                    return;
                }
                RenderTransformOrigin = new System.Windows.Point(1, 0);
                TransformGroup group = new TransformGroup();
                RenderTransform = group;

                ScaleTransform  scaleTransform = TransformGroupUtil.GetScaleTransform(group);
                DoubleAnimation da             = new DoubleAnimation(0, 1.0, new Duration(TimeSpan.FromMilliseconds(500)));
                da.BeginTime = TimeSpan.FromMilliseconds(0);
                //da.EasingFunction = easingFunction;
                da.Completed += a2_Completed;
                scaleTransform.BeginAnimation(ScaleTransform.ScaleXProperty, da);
                return;
            }

            //5.中心放大
            else if (pageSwitchType == 5)
            {
                if (isBack)
                {
                    return;
                }
                RenderTransformOrigin = new System.Windows.Point(0.5, 0.5);
                TransformGroup group = new TransformGroup();
                RenderTransform = group;


                ScaleTransform  scaleTransform = TransformGroupUtil.GetScaleTransform(group);
                DoubleAnimation da             = new DoubleAnimation(0.2, 1.0, new Duration(TimeSpan.FromMilliseconds(500)));
                da.BeginTime = TimeSpan.FromMilliseconds(0);
                IEasingFunction easingFunction = new SineEase()
                {
                    EasingMode = EasingMode.EaseOut
                };
                da.EasingFunction = easingFunction;
                da.Completed     += a2_Completed;
                scaleTransform.BeginAnimation(ScaleTransform.ScaleXProperty, da);
                scaleTransform.BeginAnimation(ScaleTransform.ScaleYProperty, da);


                Opacity = 0;
                DoubleAnimation da1 = new DoubleAnimation(0, 1.0, new Duration(TimeSpan.FromMilliseconds(100)));
                da1.BeginTime      = TimeSpan.FromMilliseconds(0);
                da1.EasingFunction = easingFunction;
                BeginAnimation(UIElement.OpacityProperty, da1);
                return;
            }
        }
示例#27
0
        protected override void OnRender(DrawingContext drawingContext)
        {
            if (_candles == null)
            {
                return;
            }

            if (_parentWindow != null)
            {
                var transform = TransformToAncestor(_parentWindow);
                var point     = transform.Transform(new Point(0, 0));

                var xOffset = point.X % 1;
                var yOffset = point.Y % 1;

                var translate = new TranslateTransform(0.5 - xOffset, 0.5 - yOffset);

                drawingContext.PushTransform(translate);
            }

            var maxDatas = (int)Math.Round(ActualWidth / 6);

            var datas = _candles.Reverse().Take(maxDatas).ToList();

            if (datas.Count <= 0)
            {
                return;
            }

            _graphContext.Period         = Period;
            _graphContext.CandleDuration = (int)Period;

            if (_graphContext.CandleDuration < 0 && datas.Count >= 2)
            {
                _graphContext.CandleDuration = (int)datas[0].Time.Subtract(datas[1].Time).TotalSeconds;
            }

            var min = double.MaxValue;
            var max = double.MinValue;

            foreach (var data in datas)
            {
                if (data.IsEmpty)
                {
                    continue;
                }

                if (data.Low < min)
                {
                    min = data.Low;
                }

                if (data.High > max)
                {
                    max = data.High;
                }
            }

            var margin = Math.Max((max - min) * 0.1, max * 0.0005);

            _graphContext.Min = min - margin;
            _graphContext.Max = max + margin;

            RenderGrid(drawingContext);

            RenderPivotPoints(drawingContext);

            var index = 0;

            foreach (var candleData in datas)
            {
                if (HideTimeGrid == false)
                {
                    RenderMinute(drawingContext, candleData, index);
                }

                RenderCandle(drawingContext, candleData, index++);
            }

            RenderLastPrice(drawingContext, datas.FirstOrDefault());

            if (Positions != null)
            {
                var positions = Positions.ToList();

                foreach (var position in positions)
                {
                    RenderPosition(drawingContext, position, datas.FirstOrDefault());
                }
            }
        }
示例#28
0
        private void RouxBackground_Loaded(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < 15; i++)
            {
                // Create a NameScope for the page so that
                // we can use Storyboards.
                NameScope.SetNameScope(this, new NameScope());

                var rotTransform   = new RotateTransform();
                var transTransform = new TranslateTransform();
                var scaleTransform = new ScaleTransform();

                // Register the transforms' names with the page
                // so that they can be targeted by a Storyboard.
                string rotateName = "AnimatedRotateTransform" + i;
                this.RegisterName(rotateName, rotTransform);
                this.RegisterName("AnimatedTranslateTransform" + i, transTransform);

                var group = new TransformGroup();
                group.Children.Add(rotTransform);
                group.Children.Add(transTransform);
                group.Children.Add(scaleTransform);

                var    star     = new Star();
                string fadeName = "Fade" + i;
                this.RegisterName(fadeName, star);
                star.Width           = star.Height = ran.Next(20, 160);
                rotTransform.CenterX = star.Width / 2;
                rotTransform.CenterY = star.Height / 2;
                star.Opacity         = ran.NextDouble();
                star.RenderTransform = group;

                // Create a Canvas to contain the star
                // and add it to the page.
                Canvas mainPanel = new Canvas();
                mainPanel.Width  = 200;
                mainPanel.Height = 200;
                mainPanel.Children.Add(star);
                uGrid1.Children.Add(mainPanel);

                // Create the animation path.
                PathGeometry movePath = new PathGeometry();
                PathFigure   pFigure  = new PathFigure();
                pFigure.StartPoint = new Point(ran.Next(minPath, maxPath), ran.Next(minPath, maxPath));
                PolyBezierSegment pBezierSegment = new PolyBezierSegment();
                pBezierSegment.Points.Add(new Point(ran.Next(minPath, maxPath), ran.Next(minPath, maxPath)));
                pBezierSegment.Points.Add(new Point(ran.Next(minPath, maxPath), ran.Next(minPath, maxPath)));
                pBezierSegment.Points.Add(new Point(ran.Next(minPath, maxPath), ran.Next(minPath, maxPath)));

                pFigure.Segments.Add(pBezierSegment);
                movePath.Figures.Add(pFigure);

                // Freeze the PathGeometry for performance benefits.
                movePath.Freeze();

                Path p = new Path();
                p.Data   = movePath;
                p.Stroke = new SolidColorBrush(Colors.Red);


                double length = ran.Next(8, 45);


                DoubleAnimation da  = SetupRotationAnimation(i, rotateName);
                DoubleAnimation da2 = SetupFadeAnimation(i, length, fadeName);

                // Create a DoubleAnimationUsingPath to move the
                // rectangle horizontally along the path by animating
                // its TranslateTransform.
                DoubleAnimationUsingPath translateXAnimation = new DoubleAnimationUsingPath();
                translateXAnimation.PathGeometry = movePath;
                translateXAnimation.Duration     = TimeSpan.FromSeconds(length);

                translateXAnimation.Source = PathAnimationSource.X;

                Storyboard.SetTargetName(translateXAnimation, "AnimatedTranslateTransform" + i);
                Storyboard.SetTargetProperty(translateXAnimation,
                                             new PropertyPath(TranslateTransform.XProperty));

                DoubleAnimationUsingPath translateYAnimation = new DoubleAnimationUsingPath();
                //	translateYAnimation.RepeatBehavior = RepeatBehavior.Forever;
                translateYAnimation.PathGeometry = movePath;
                translateYAnimation.Duration     = TimeSpan.FromSeconds(length);

                translateYAnimation.Source = PathAnimationSource.Y;

                Storyboard.SetTargetName(translateYAnimation, "AnimatedTranslateTransform" + i);
                Storyboard.SetTargetProperty(translateYAnimation,
                                             new PropertyPath(TranslateTransform.YProperty));

                // Create a Storyboard to contain and apply the animations.
                Storyboard spinSB = new Storyboard();
                spinSB.Children.Add(da);
                spinSB.Begin(this);

                // Create a Storyboard to contain and apply the animations.
                Storyboard fadeSB = new Storyboard();
                fadeSB.Duration       = TimeSpan.FromSeconds(length);
                fadeSB.AutoReverse    = true;
                fadeSB.RepeatBehavior = RepeatBehavior.Forever;
                fadeSB.Children.Add(da2);
                fadeSB.Begin(this);

                Storyboard pathAnimationStoryboard = new Storyboard();
                pathAnimationStoryboard.RepeatBehavior = RepeatBehavior.Forever;
                pathAnimationStoryboard.AutoReverse    = true;
                //	pathAnimationStoryboard.Children.Add(da2);
                pathAnimationStoryboard.Children.Add(translateXAnimation);
                pathAnimationStoryboard.Children.Add(translateYAnimation);
                pathAnimationStoryboard.Begin(this);
            }
        }
示例#29
0
        private void UpdateGrid(bool withAnimation)
        {
            TimeSpan animationTime = new TimeSpan();
            List <WidgetSiteControl> sitesToRemove = new List <WidgetSiteControl>(256);

            int rowCount    = _controlData.Source.Bounds.RowCount;
            int columnCount = _controlData.Source.Bounds.ColumnCount;

            ResizeRowOrColumn(matrixPanel.RowDefinitions, rowCount);
            ResizeRowOrColumn(matrixPanel.ColumnDefinitions, columnCount);

            _controlData.SiteGrid = new Array2D <WidgetSiteControl>(rowCount, columnCount);

            foreach (var child in matrixPanel.Children)
            {
                WidgetSiteControl site = child as WidgetSiteControl;

                if (site == null)
                {
                    continue;
                }

                if (!_controlData.Source.Bounds.Contains(site.Location))
                {
                    if (withAnimation)
                    {
                        MatrixSize siteDistance = _controlData.Source.Bounds.Distance(site.Location);

                        TranslateTransform transform = (TranslateTransform)((TransformGroup)site.RenderTransform).Children[1];

                        transform.Y = site.HeightWithMargin * siteDistance.RowCount;
                        transform.X = site.WidthWithMargin * siteDistance.ColumnCount;

                        AnimateSiteScaleTransform(site, ref animationTime, 1, 0,
                                                  new EventHandler((o, e) => {
                            matrixPanel.Children.Remove(site);
                        }));
                    }
                    else
                    {
                        sitesToRemove.Add(site);
                    }
                }
                else
                {
                    MatrixLoc arrayIndex = _controlData.Source.Bounds.ToIndex(site.Location);

                    _controlData.SiteGrid[arrayIndex] = site;

                    site.UpdateGridPosition();
                }
            }

            foreach (var site in sitesToRemove)
            {
                matrixPanel.Children.Remove(site);
            }

            foreach (MatrixLoc loc in _controlData.Source.Bounds)
            {
                MatrixLoc arrayIndex = _controlData.Source.Bounds.ToIndex(loc);

                if (_controlData.SiteGrid[arrayIndex] == null)
                {
                    var site = CreateWidgetSite(loc, withAnimation, ref animationTime);

                    _controlData.SiteGrid[arrayIndex] = site;
                }

                _controlData.SiteGrid[arrayIndex].Content = _controlData.Source[loc];
            }
        }
        /// <summary>
        /// Performs the layout for all child controls.
        /// </summary>
        /// <param name="finalSize">The space available for the panel to display its child objects.</param>
        /// <returns>Size of the panel.</returns>
        protected override Size ArrangeOverride(Size finalSize)
        {
            base.ArrangeOverride(finalSize);

            double top            = 0;
            double left           = 0;
            bool   widthInfinity  = false;
            bool   heightInfinity = false;
            double greatestHeight = 0;
            double greatestWidth  = 0;

            // Check finalSize does not return infinity
            if (double.IsInfinity(finalSize.Width))
            {
                widthInfinity = true;
            }

            if (double.IsInfinity(finalSize.Height))
            {
                heightInfinity = true;
            }

            foreach (FrameworkElement child in this.Children)
            {
                if (this.wrapDirection == WrapDirection.Horizontal)
                {
                    // If infinite space is available, keep positioning left to right
                    // If not, check to see if we have reached our furthest position
                    if (!widthInfinity)
                    {
                        if (left + child.DesiredSize.Width > finalSize.Width)
                        {
                            // Set top for new line and reset left and greatestHeight properties
                            top += greatestHeight;

                            left           = 0;
                            greatestHeight = 0;
                        }
                    }
                }
                else
                {
                    // If infinite space is available, keep positioning top to bottom
                    // If not, check to see if we have reached our furthest position
                    if (!heightInfinity)
                    {
                        if (top + child.DesiredSize.Height > finalSize.Height)
                        {
                            // Set top for new line and reset left and greatestHeight properties
                            left += greatestWidth;

                            top           = 0;
                            greatestWidth = 0;
                        }
                    }
                }

                // Create child within panel
                child.Arrange(new Rect(0, 0, child.DesiredSize.Width, child.DesiredSize.Height));

                // Ensure the child item has a unique name
                this.ConfirmItemName(child);

                // Get the information about the Transform applied to the item
                TransformInformation information = this.ConfirmTransform(child);

                TranslateTransform translate = information.TranslateTransform;

                // Set child element position to where it is currently
                if (!this.AnimateOnInitialise && !this.performedInitialLayout)
                {
                    // Set in correct position
                    translate.X = left;
                    translate.Y = top;
                }

                // Get the Storyboard for the child item
                Storyboard storyboard = this.ConfirmStoryboard(child, information.PositionInCollection);

                // Configure animation properties for translateX
                DoubleAnimation leftAnim = (DoubleAnimation)storyboard.Children[0];
                leftAnim.To = left;

                // Configure animation properties for translateX
                DoubleAnimation topAnim = (DoubleAnimation)storyboard.Children[1];
                topAnim.To = top;

                // Check if the item is new and set FROM property accordingly
                if (!GetDisableEntrance(child) && this.EntranceAnimationEnabled)
                {
                    // Set FROM Property
                    Point enterFrom = this.GetEntryPosition(child);
                    leftAnim.From = enterFrom.X;
                    topAnim.From  = enterFrom.Y;
                    translate.X   = enterFrom.X;
                    translate.Y   = enterFrom.Y;
                    SetDisableEntrance(child, true);
                }
                else if (!GetDisableEntrance(child) && !this.EntranceAnimationEnabled)
                {
                    leftAnim.From = left;
                    topAnim.From  = top;
                    SetDisableEntrance(child, true);
                }
                else
                {
                    leftAnim.From = null;
                    topAnim.From  = null;
                    SetDisableEntrance(child, true);
                }

                // Begin the Storyboard
                storyboard.Begin();

#if SILVERLIGHT
                // Check if the item is a design-time entrance preview
                // Provide design-time preview of entrance
                if (DesignerProperties.GetIsInDesignMode(Application.Current.RootVisual))
                {
                    storyboard.Completed += new EventHandler(this.EntrancePreviewStoryboard_Completed);
                }
#endif

                // Increment the positioning variables based on orientation
                if (this.wrapDirection == WrapDirection.Horizontal)
                {
                    left += child.DesiredSize.Width;
                }
                else
                {
                    top += child.DesiredSize.Height;
                }

                // Keep track of greatest height and width on this line of items
                if (child.DesiredSize.Width > greatestWidth)
                {
                    greatestWidth = child.DesiredSize.Width;
                }

                if (child.DesiredSize.Height > greatestHeight)
                {
                    greatestHeight = child.DesiredSize.Height;
                }
            }

            // Indicate that the panel has completed the first layout pass
            this.performedInitialLayout = true;

            // Clip out of bound content
            RectangleGeometry rectangleGeometry = new RectangleGeometry();
            Rect clip = new Rect(new Point(0, 0), new Size(finalSize.Width, finalSize.Height));
            rectangleGeometry.Rect = clip;
            this.Clip = rectangleGeometry;

            return(finalSize);
        }
示例#31
0
        /// <summary>
        /// Convenience function to translate an atom symbol on a specified point.
        /// </summary>
        /// <param name="x">x-axis location</param>
        /// <param name="y">y-axis location</param>
        /// <returns>the translated symbol (new instance)</returns>
        public AtomSymbol Translate(double x, double y)
        {
            var m = new TranslateTransform(x, y);

            return(Transform(m));
        }
        public FrameworkContentElementStoryboardWithHandoffBehaviorExample()
        {
            // Create a name scope for the document.
            NameScope.SetNameScope(this, new NameScope());
            this.Background = Brushes.Orange;

            // Create a run of text.
            Run theText = new Run(
                "Lorem ipsum dolor sit amet, consectetuer adipiscing elit.");

            // Create a TextEffect
            TextEffect animatedSpecialEffect = new TextEffect();

            animatedSpecialEffect.Foreground    = Brushes.OrangeRed;
            animatedSpecialEffect.PositionStart = 0;
            animatedSpecialEffect.PositionCount = 20;

            TranslateTransform animatedTransform =
                new TranslateTransform();

            // Assign the transform a name by
            // registering it with the page, so that
            // it can be targeted by storyboard
            // animations.
            this.RegisterName("animatedTransform", animatedTransform);
            animatedSpecialEffect.Transform = animatedTransform;

            // Apply the text effect to the run.
            theText.TextEffects = new TextEffectCollection();
            theText.TextEffects.Add(animatedSpecialEffect);

            // Create a paragraph to contain the run.
            Paragraph animatedParagraph = new Paragraph(theText);

            animatedParagraph.Background = Brushes.LightGray;

            this.Blocks.Add(animatedParagraph);

            //
            // Create a storyboard to animate the
            // text effect's transform.
            //
            myStoryboard = new Storyboard();

            xAnimation          = new DoubleAnimation();
            xAnimation.Duration = TimeSpan.FromSeconds(5);
            Storyboard.SetTargetName(xAnimation, "animatedTransform");
            Storyboard.SetTargetProperty(xAnimation,
                                         new PropertyPath(TranslateTransform.XProperty));
            myStoryboard.Children.Add(xAnimation);

            yAnimation          = new DoubleAnimation();
            yAnimation.Duration = TimeSpan.FromSeconds(5);
            Storyboard.SetTargetName(yAnimation, "animatedTransform");
            Storyboard.SetTargetProperty(yAnimation,
                                         new PropertyPath(TranslateTransform.YProperty));
            myStoryboard.Children.Add(yAnimation);

            this.MouseLeftButtonDown +=
                new MouseButtonEventHandler(document_mouseLeftButtonDown);
            this.MouseRightButtonDown +=
                new MouseButtonEventHandler(document_mouseRightButtonDown);
        }
示例#33
0
        protected override void Init()
        {
            SetBaseView();

            TranslateTransform translation = new TranslateTransform(0, 0);

            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 TranslateTransform(0, 0);
                Win.RegisterName(translation.GetHashCode().ToString(), translation);
                tg.Children.Add(translation);
                Element.RenderTransform = tg;
            }
            else
            {
                var tg = ex as TransformGroup;
                foreach (var item in tg.Children)
                {
                    translation = item as TranslateTransform;
                    if (translation != null)
                    {
                        break;
                    }
                }
                if (translation != null)
                {
                    //当前Y值
                    var tex = translation.GetValue(FrameworkElement.NameProperty);
                    if (tex != null && tex.ToString() != "")
                    {
                    }
                    else
                    {
                        Win.RegisterName(translation.GetHashCode().ToString(), translation);
                    }
                }
                else
                {
                    translation = new TranslateTransform(0, 0);
                    Win.RegisterName(translation.GetHashCode().ToString(), translation);
                    tg.Children.Add(translation);
                    Element.RenderTransform = tg;
                }
            }
            #endregion

            if (FromDistance == 0)
            {
                FromDistance = Element.RenderSize.Width * 1.5;
            }


            var k2 = new EasingDoubleKeyFrame(FromDistance, TimeSpan.FromMilliseconds(AniTime(0)));
            var k3 = new EasingDoubleKeyFrame(ToDistance, TimeSpan.FromMilliseconds(AniTime(1)));
            if (EasingFunction != null)
            {
                k3.EasingFunction = EasingFunction;
            }

            Storyboard.SetTargetName(dau, Win.GetName(translation));

            Storyboard.SetTargetProperty(dau, new PropertyPath(TranslateTransform.XProperty));
            dau.FillBehavior = AniEndBehavior;

            Win.RegisterResource(Story);
            Story = (Storyboard)Story.CloneCurrentValue();
            dau.KeyFrames.Add(k2);
            dau.KeyFrames.Add(k3);
            Story.Children.Add(dau);


            if (OpacityNeed)
            {
                dauOpacty = new DoubleAnimationUsingKeyFrames();
                var k6   = new EasingDoubleKeyFrame(0, TimeSpan.FromMilliseconds(AniTime(0)));
                var k6_1 = new EasingDoubleKeyFrame(1, TimeSpan.FromMilliseconds(AniTime(1)));

                dauOpacty.KeyFrames.Add(k6);
                dauOpacty.KeyFrames.Add(k6_1);
                Storyboard.SetTarget(dauOpacty, Element);
                dauOpacty.FillBehavior = FillBehavior.Stop;
                Storyboard.SetTargetProperty(dauOpacty, new PropertyPath(UIElement.OpacityProperty));
                Story.Children.Add(dauOpacty);
            }


            Story.Completed += Story_Completed;
        }
        /// <summary>
        ///      Creates the brush for the ProgressBar
        /// </summary>
        /// <param name="values">ForegroundBrush, IsIndeterminate, Width, Height</param>
        /// <param name="targetType"></param>
        /// <param name="parameter"></param>
        /// <param name="culture"></param>
        /// <returns>Brush for the ProgressBar</returns>
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            //
            // Parameter Validation
            //
            Type doubleType = typeof(double);

            if (values == null ||
                (values.Length != 3) ||
                (values[0] == null) ||
                (values[1] == null) ||
                (values[2] == null) ||
                !typeof(Brush).IsAssignableFrom(values[0].GetType()) ||
                !doubleType.IsAssignableFrom(values[1].GetType()) ||
                !doubleType.IsAssignableFrom(values[2].GetType()))
            {
                return(null);
            }

            //
            // Conversion
            //

            Brush  brush  = (Brush)values[0];
            double width  = (double)values[1];
            double height = (double)values[2];

            // if an invalid height, return a null brush
            if (width <= 0.0 || Double.IsInfinity(width) || Double.IsNaN(width) ||
                height <= 0.0 || Double.IsInfinity(height) || Double.IsNaN(height))
            {
                return(null);
            }

            DrawingBrush newBrush = new DrawingBrush();

            // Create a Drawing Brush that is 2x longer than progress bar track
            //
            // +-------------+..............
            // | highlight   | empty       :
            // +-------------+.............:
            //
            //  This brush will animate to the right.

            double twiceWidth = width * 2.0;

            // Set the viewport and viewbox to the 2*size of the progress region
            newBrush.Viewport      = newBrush.Viewbox = new Rect(-width, 0, twiceWidth, height);
            newBrush.ViewportUnits = newBrush.ViewboxUnits = BrushMappingMode.Absolute;

            newBrush.TileMode = TileMode.None;
            newBrush.Stretch  = Stretch.None;

            DrawingGroup   myDrawing        = new DrawingGroup();
            DrawingContext myDrawingContext = myDrawing.Open();

            // Draw the highlight
            myDrawingContext.DrawRectangle(brush, null, new Rect(-width, 0, width, height));


            // Animate the Translation

            TimeSpan translateTime = TimeSpan.FromSeconds(twiceWidth / 200.0); // travel at 200px /second
            TimeSpan pauseTime     = TimeSpan.FromSeconds(1.0);                // pause 1 second between animations

            DoubleAnimationUsingKeyFrames animation = new DoubleAnimationUsingKeyFrames();

            animation.BeginTime      = TimeSpan.Zero;
            animation.Duration       = new Duration(translateTime + pauseTime);
            animation.RepeatBehavior = RepeatBehavior.Forever;
            animation.KeyFrames.Add(new LinearDoubleKeyFrame(twiceWidth, translateTime));

            TranslateTransform translation = new TranslateTransform();

            // Set the animation to the XProperty
            translation.BeginAnimation(TranslateTransform.XProperty, animation);

            // Set the animated translation on the brush
            newBrush.Transform = translation;


            myDrawingContext.Close();
            newBrush.Drawing = myDrawing;

            return(newBrush);
        }
示例#35
0
        public void AddGraphPort(IGraphPort aPort)
        {
            SetPixelHandler += new NewTOAPIA.Drawing.SetPixel(aPort.SetPixel);

            DrawLineHandler += new DrawLine(aPort.DrawLine);
            DrawLinesHandler += new DrawLines(aPort.DrawLines);

            DrawRectangleHandler += new NewTOAPIA.Drawing.DrawRectangle(aPort.DrawRectangle);
            DrawRectanglesHandler += new NewTOAPIA.Drawing.DrawRectangles(aPort.DrawRectangles);
            FillRectangleHandler += new NewTOAPIA.Drawing.FillRectangle(aPort.FillRectangle);

            DrawEllipseHandler += new NewTOAPIA.Drawing.DrawEllipse(aPort.DrawEllipse);
            FillEllipseHandler += new NewTOAPIA.Drawing.FillEllipse(aPort.FillEllipse);

            DrawRoundRectHandler += new NewTOAPIA.Drawing.DrawRoundRect(aPort.DrawRoundRect);

            PolygonHandler += new NewTOAPIA.Drawing.Polygon(aPort.Polygon);
            DrawBeziersHandler += new NewTOAPIA.Drawing.DrawBeziers(aPort.DrawBeziers);
            
            DrawPathHandler += new NewTOAPIA.Drawing.DrawPath(aPort.DrawPath);
            FillPathHandler += new FillPath(aPort.FillPath);

            //// Gradient fills
            //DrawGradientRectangleHandler += new NewTOAPIA.Drawing.DrawGradientRectangle(aPort.DrawGradientRectangle);

            //// Drawing Text
            DrawStringHandler += new NewTOAPIA.Drawing.DrawString(aPort.DrawString);

            ///// Draw bitmaps
            PixBltHandler += new NewTOAPIA.Drawing.PixBlt(aPort.PixBlt);
            //PixmapShardBltHandler += new NewTOAPIA.Drawing.PixmapShardBlt(aPort.PixmapShardBlt);
            //AlphaBlendHandler += new NewTOAPIA.Drawing.AlphaBlend(aPort.AlphaBlend);

            // Path handling
            //DrawPathHandler += new NewTOAPIA.Drawing.DrawPath(aPort.DrawPath);
            //SetPathAsClipRegionHandler += new NewTOAPIA.Drawing.SetPathAsClipRegion(aPort.SetPathAsClipRegion);

            //// Setting some objects
            SetPenHandler += new NewTOAPIA.Drawing.SetPen(aPort.SetPen);
            SetBrushHandler += new SetBrush(aPort.SetBrush);
            SetFontHandler += new SetFont(aPort.SetFont);

            //SelectStockObjectHandler += new NewTOAPIA.Drawing.SelectStockObject(aPort.SelectStockObject);
            SelectUniqueObjectHandler += new NewTOAPIA.Drawing.SelectUniqueObject(aPort.SelectUniqueObject);

            //// State Management
            FlushHandler += new NewTOAPIA.Drawing.Flush(aPort.Flush);
            SaveStateHandler += new NewTOAPIA.Drawing.SaveState(aPort.SaveState);
            ResetStateHandler += new NewTOAPIA.Drawing.ResetState(aPort.ResetState);
            RestoreStateHandler += new NewTOAPIA.Drawing.RestoreState(aPort.RestoreState);

            //// Setting Attributes and modes
            SetTextColorHandler += new NewTOAPIA.Drawing.SetTextColor(aPort.SetTextColor);

            //// Setting some modes
            SetBkColorHandler += new NewTOAPIA.Drawing.SetBkColor(aPort.SetBkColor);
            SetBkModeHandler += new NewTOAPIA.Drawing.SetBkMode(aPort.SetBkMode);

            SetMappingModeHandler += new NewTOAPIA.Drawing.SetMappingMode(aPort.SetMappingMode);
            SetPolyFillModeHandler += new NewTOAPIA.Drawing.SetPolyFillMode(aPort.SetPolyFillMode);
            SetROP2Handler += new NewTOAPIA.Drawing.SetROP2(aPort.SetROP2);

            SetClipRectangleHandler += new SetClipRectangle(aPort.SetClipRectangle);

            // World transform management
            SetWorldTransformHandler += new NewTOAPIA.Drawing.SetWorldTransform(aPort.SetWorldTransform);
            TranslateTransformHandler += new TranslateTransform(aPort.TranslateTransform);
            ScaleTransformHandler += new ScaleTransform(aPort.ScaleTransform);
            RotateTransformHandler += new RotateTransform(aPort.RotateTransform);
        }
示例#36
0
        private void loadNewImages()
        {
            //MonochromeEffect monoFX = new MonochromeEffect();
            //monoFX.FilterColor = Color.FromArgb(0, 255, 255, 255);
            //monoFX.Contrast = 1.5;

            for (int j = 0; j < _currentImgsIndex.Count; j++)
            {
                // This blocks be careful
                BitmapImage currentImage = new BitmapImage();
                currentImage.BeginInit();
                //currentImage.DecodePixelWidth = 640;
                //currentImage.DecodePixelHeight = 480;
                currentImage.CreateOptions = BitmapCreateOptions.IgnoreColorProfile;
                currentImage.CacheOption   = BitmapCacheOption.OnLoad;
                currentImage.UriSource     = new Uri(_allImageData[_currentImgsIndex[j]].toLoadPath);
                currentImage.EndInit();
                //currentImage.Freeze();

                Image MainImg = new Image();
                MainImg.Stretch = Stretch.Uniform;
                MainImg.Opacity = 1;
                MainImg.Source  = currentImage;
                //monoFX.Contrast = (double)(_rand.Next(1, 3) + _rand.NextDouble());
                //MainImg.Effect = monoFX;

                Border myBorder = new Border();
                myBorder.BorderThickness     = new Thickness(10);
                myBorder.BorderBrush         = new SolidColorBrush(Colors.White);
                myBorder.Margin              = new Thickness(8.0);
                myBorder.Opacity             = 1;
                myBorder.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                myBorder.VerticalAlignment   = System.Windows.VerticalAlignment.Top;
                myBorder.Child = MainImg;

                // Figure out a random placement and tilted angle on the display
                // -45 to 45
                //int angle = _rand.Next(-10, 10);

                // We know that the scroller needs 200 px
                // We know the actual bar needs 74
                double availableWidth = GlobalConfiguration.currentScreenW - 640 - 50;

                // Need to account for bottom of screen 250
                // Need to account for image height 480
                // Need to account for rotated image height 240

                double availableHeight = GlobalConfiguration.currentScreenH - 250 - 480;

                Point newXY = new Point(_rand.Next(50, (int)availableWidth), _rand.Next(0, (int)availableHeight));
                // We want all items all the way to the left or right of the screen
                int lOrR = _rand.Next(0, 100);
                if (lOrR > 50)
                {
                    newXY.X = GlobalConfiguration.currentScreenW + 300;
                }
                else
                {
                    newXY.X = -1000;
                }

                int tOrB = _rand.Next(0, 100);
                if (tOrB > 50)
                {
                    newXY.Y = GlobalConfiguration.currentScreenH + 300;
                }
                else
                {
                    newXY.Y = -1000;
                }

                // Set the tag property to the point
                myBorder.SetValue(FrameworkElement.TagProperty, newXY);

                // Transforms for moving and rotating
                TranslateTransform moveTransform = new TranslateTransform(newXY.X, newXY.Y);
                //RotateTransform rotTransform = new RotateTransform(angle);
                TransformGroup photoTransforms = new TransformGroup();
                photoTransforms.Children.Add(moveTransform);
                //photoTransforms.Children.Add(rotTransform);

                myBorder.RenderTransform = photoTransforms;
                mainHolder.Children.Add(myBorder);
            }
        }
        private void gridPad_PointerMoved(object sender, PointerRoutedEventArgs e)
        {
            IList <Windows.UI.Input.PointerPoint> IlistPointer = e.GetIntermediatePoints(gridPad);
            int intPointerCount = IlistPointer.Count();

            byte[] rgb = new byte[3];
            (new Random()).NextBytes(rgb);
            Color color = Color.FromArgb(255, rgb[0], rgb[1], rgb[2]);

            var blnIsMouse = e.Pointer.PointerDeviceType == PointerDeviceType.Mouse;

            //Pointer saved in reversed mode ...
            for (int i = intPointerCount - 1; i >= 0; i--)
            {
                Windows.UI.Input.PointerPoint pointer = IlistPointer[i];

                // User PointerId for identify sequence (line) - if needed
                setId.Add(pointer.PointerId); // Add to Set - Set Automatically does not include duplicate Id ...

                Point point = pointer.Position;

                // Prevent adding ellipse if mouse over grid and not left pressed ...
                if (blnIsMouse && !pointer.Properties.IsLeftButtonPressed)
                {
                    continue;
                }

                //Properties -  https://msdn.microsoft.com/en-us/library/windows.ui.input.pointerpointproperties.aspx
                //if your devise has stylus ...
                float pressure = pointer.Properties.Pressure;

                // 48 just randomly chosen value...
                // value pressure always 0.5 if not pen (stylus) ...


                // Pay attention about simulator - pressure will be very small
                pressure = 1;  // use for simulate

                double w = 48.0 * pressure;
                double h = 48.0 * pressure;

                if (point.X < w / 2.0 || point.X > gridPad.ActualWidth - w / 2)
                {
                    continue;  // add ellipse only on grid
                }

                if (point.Y < h / 2.0 || point.Y > gridPad.ActualHeight - h / 2)
                {
                    continue; // add ellipse only on grid
                }

                var tr = new TranslateTransform();
                tr.X = point.X - gridPad.ActualWidth / 2.0;
                tr.Y = point.Y - gridPad.ActualHeight / 2.0;

                Ellipse el = new Ellipse()
                {
                    Width           = w,
                    Height          = h,
                    Fill            = new SolidColorBrush(color),
                    RenderTransform = tr,
                    Visibility      = Visibility.Visible
                };

                gridPad.Children.Add(el);
            }

            txtInfo.Text = " " + setId.Count().ToString() + " lines ...";

            // base.OnPointerMoved(e); //You can see differences if uncomment this line
        }
        private void Control_MouseMove(object sender, MouseEventArgs e)
        {
            var draggableControl = sender as UserControl;

            if (isDragging && draggableControl != null)
            {
                Point currentPosition = e.GetPosition(this.Parent as UIElement);

                var transform = draggableControl.RenderTransform as TranslateTransform;
                if (transform == null)
                {
                    transform = new TranslateTransform();
                    draggableControl.RenderTransform = transform;
                }

                transform.X = currentPosition.X - clickPosition.X;
                transform.Y = currentPosition.Y - clickPosition.Y;
            }
        }
示例#39
0
        /// <summary>
        /// Does a recursive deep copy of the specified transform.
        /// </summary>
        /// <param name="transform">The transform to clone.</param>
        /// <returns>A deep copy of the specified transform, or null if the specified transform is null.</returns>
        /// <exception cref="System.ArgumentException">Thrown if the type of the Transform is not recognized.</exception>
        internal static Transform CloneTransform(Transform transform)
        {
            ScaleTransform     scaleTransform     = null;
            RotateTransform    rotateTransform    = null;
            SkewTransform      skewTransform      = null;
            TranslateTransform translateTransform = null;
            MatrixTransform    matrixTransform    = null;
            TransformGroup     transformGroup     = null;

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

            Type transformType = transform.GetType();

            if ((scaleTransform = transform as ScaleTransform) != null)
            {
                return(new ScaleTransform()
                {
                    CenterX = scaleTransform.CenterX,
                    CenterY = scaleTransform.CenterY,
                    ScaleX = scaleTransform.ScaleX,
                    ScaleY = scaleTransform.ScaleY,
                });
            }
            else if ((rotateTransform = transform as RotateTransform) != null)
            {
                return(new RotateTransform()
                {
                    Angle = rotateTransform.Angle,
                    CenterX = rotateTransform.CenterX,
                    CenterY = rotateTransform.CenterY,
                });
            }
            else if ((skewTransform = transform as SkewTransform) != null)
            {
                return(new SkewTransform()
                {
                    AngleX = skewTransform.AngleX,
                    AngleY = skewTransform.AngleY,
                    CenterX = skewTransform.CenterX,
                    CenterY = skewTransform.CenterY,
                });
            }
            else if ((translateTransform = transform as TranslateTransform) != null)
            {
                return(new TranslateTransform()
                {
                    X = translateTransform.X,
                    Y = translateTransform.Y,
                });
            }
            else if ((matrixTransform = transform as MatrixTransform) != null)
            {
                return(new MatrixTransform()
                {
                    Matrix = matrixTransform.Matrix,
                });
            }
            else if ((transformGroup = transform as TransformGroup) != null)
            {
                TransformGroup group = new TransformGroup();
                foreach (Transform childTransform in transformGroup.Children)
                {
                    group.Children.Add(CloneTransform(childTransform));
                }
                return(group);
            }

            Debug.Assert(false, "Unexpected Transform type encountered");
            return(null);
        }
示例#40
0
 override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            _suppressAnimations = false;

            _itemsList = GetTemplateChild(ItemsListName) as ItemsPresenter;
#if WINDOWS_PHONE
            _itemsList.CacheMode = new BitmapCache();
#endif
            _translate = GetTemplateChild(SlidingTransformName) as TranslateTransform;
        }
示例#41
0
        private void CreateUI()
        {
            var container = new Grid();

            var data = JsonConvert.DeserializeObject <UIDesignModel>(FileHelper.Read($"UI\\{ScreenName}.json"));

            if (data == null)
            {
                data = GetDefaultUI();
                FileHelper.Write($"UI\\{ScreenName}.json", JsonConvert.SerializeObject(data));
            }
            var containerBG = new Border();

            containerBG.Width  = Double.NaN;
            containerBG.Height = Double.NaN;
            containerBG.SetValue(Grid.ZIndexProperty, -1);
            containerBG.Background = data.ContainerAttr.Background;
            containerBG.Opacity    = data.ContainerAttr.Opacity;
            container.Children.Add(containerBG);
            foreach (var element in data.Elements)
            {
                var ttf = new TranslateTransform()
                {
                    X = element.X,
                    Y = element.Y
                };
                switch (element.Type)
                {
                case Project1.UI.Controls.Enums.DesignItemType.Text:
                    var textElement = CreateTextElemenet(element);
                    textElement.RenderTransform = ttf;
                    container.Children.Add(textElement);
                    break;

                case Project1.UI.Controls.Enums.DesignItemType.Button:
                    var buttonElement = CreateButtonElement(element);
                    buttonElement.RenderTransform = ttf;
                    container.Children.Add(buttonElement);
                    break;

                case Project1.UI.Controls.Enums.DesignItemType.Image:
                    var imageElement = new Image();
                    imageElement.HorizontalAlignment = HorizontalAlignment.Left;
                    imageElement.VerticalAlignment   = VerticalAlignment.Top;
                    imageElement.RenderTransform     = ttf;
                    imageElement.Width   = element.Width;
                    imageElement.Height  = element.Height;
                    imageElement.Opacity = element.Opacity;
                    imageElement.Stretch = Stretch.Fill;
                    try
                    {
                        //imageElement.Source = new BitmapImage(new Uri(element.Image, UriKind.RelativeOrAbsolute));
                        imageElement.Source = BitmapImager.Load(element.Image);
                    }
                    catch
                    {
                        imageElement.Source = BitmapImager.Load("pack://application:,,,/Project1.UI;component/Assets/Images/sunglasses.png");
                        //imageElement.Source = new BitmapImage(new Uri("pack://application:,,,/Project1.UI;component/Assets/Images/sunglasses.png", UriKind.RelativeOrAbsolute));
                    }
                    container.Children.Add(imageElement);
                    break;
                }
            }



            WindowInstance.Content = container;
        }
示例#42
0
        /// <summary>
        /// 创建新粒子
        /// </summary>
        /// <param name="canvas"></param>
        /// <param name="e"></param>
        /// <param name="particles"></param>
        private void SpawnParticle(Canvas canvas, Ellipse e, List <Particle> particles)
        {
            //粒子型号
            double size  = Rand.Next(MinSize, MaxSize);
            double x     = Rand.Next(X1, X2) - size / 2;
            double y     = Rand.Next(Y1, Y2) - size / 2;
            double z     = 0;
            double speed = Rand.Next(MinSpeed, MaxSpeed);

            Particle p = new Particle()
            {
                Position = new Point3D(x, y, z),
                Size     = size,
            };

            //模糊
            var blur = new BlurEffect();

            blur.RenderingBias = RenderingBias.Performance;
            blur.Radius        = Rand.Next(MinRadius, MaxRadius);
            p.Blur             = blur;

            //画刷
            var brush = ParticlesBrush.Clone();

            brush.Opacity = Rand.Next(MinOpacity, MaxOpacity);
            p.Brush       = brush;

            //平移变换
            TranslateTransform t;

            if (e != null)
            {
                e.Fill    = null;
                e.Width   = e.Height = size;
                p.Ellipse = e;

                t = e.RenderTransform as TranslateTransform;
            }
            else
            {
                p.Ellipse = new Ellipse()
                {
                    Width = size, Height = size, IsEnabled = false, IsHitTestVisible = false
                };
                canvas.Children.Add(p.Ellipse);

                t = new TranslateTransform();
                p.Ellipse.RenderTransform       = t;
                p.Ellipse.RenderTransformOrigin = new Point(size / 2, size / 2);
            }

            t.X = p.Position.X;
            t.Y = p.Position.Y;

            double vX = Rand.Next(X1D[(int)Direction], X2D[(int)Direction]) * speed;
            double vY = Rand.Next(Y1D[(int)Direction], Y2D[(int)Direction]) * speed;

            p.Velocity = new Point3D(vX, vY, 0);

            particles.Add(p);
        }
示例#43
0
        private void RefreshBackground()
        {
            if (_container != null)
            {
                if (_background != null)
                {
                    _container.Children.Remove(_background);
                }

                _background = this.BackgroundTemplate.LoadContent() as FrameworkElement;
                _container.Children.Insert(0, _background);

                if (!(this._background.RenderTransform is TranslateTransform))
                {
                    this._background.RenderTransform = new TranslateTransform();
                }

                this._backgroundTransform = this._background.RenderTransform as TranslateTransform;

                this._background.SizeChanged += _scrollViewer_SizeChanged;
            }
        }