WPF. Easiest way to move Image to (X,Y) programmatically?

前端 未结 5 1507
谎友^
谎友^ 2020-11-30 12:52

Does anyone know of an easy way to animate a movement from an Image\'s current location to a new location (X,Y) using WPF animation with no XAML, 100% programmatically? And

5条回答
  •  日久生厌
    2020-11-30 13:18

    Here it is... It changes the size and moves a MediaElement under the Canvas. Just input your parameters:

    Storyboard story = new Storyboard();
    DoubleAnimation dbWidth = new DoubleAnimation();
    dbWidth.From = mediaElement1.Width;
    dbWidth.To = 600;
    dbWidth.Duration = new Duration(TimeSpan.FromSeconds(.25));
    
    DoubleAnimation dbHeight = new DoubleAnimation();
    dbHeight.From = mediaElement1.Height;
    dbHeight.To = 400;
    dbHeight.Duration = dbWidth.Duration;
    
    story.Children.Add(dbWidth);
    Storyboard.SetTargetName(dbWidth, mediaElement1.Name);
    Storyboard.SetTargetProperty(dbWidth, new PropertyPath(MediaElement.WidthProperty));
    
    story.Children.Add(dbHeight);
    Storyboard.SetTargetName(dbHeight, mediaElement1.Name);
    Storyboard.SetTargetProperty(dbHeight, new PropertyPath(MediaElement.HeightProperty));
    
    DoubleAnimation dbCanvasX = new DoubleAnimation();
    dbCanvasX.From = 0;
    dbCanvasX.To = 5;
    dbCanvasX.Duration = new Duration(TimeSpan.FromSeconds(.25));
    
    DoubleAnimation dbCanvasY = new DoubleAnimation();
    dbCanvasY.From = 0;
    dbCanvasY.To = 5;
    dbCanvasY.Duration = dbCanvasX.Duration;
    
    story.Children.Add(dbCanvasX);
    Storyboard.SetTargetName(dbCanvasX, mediaElement1.Name);
    Storyboard.SetTargetProperty(dbCanvasX, new PropertyPath(Canvas.LeftProperty));
    
    story.Children.Add(dbCanvasY);
    Storyboard.SetTargetName(dbCanvasY, mediaElement1.Name);
    Storyboard.SetTargetProperty(dbCanvasY, new PropertyPath(Canvas.TopProperty));
    
    story.Begin(this);
    

    
            
                
                    
                    

    UPDATE:

    Instead of MediaElement use this line:

     
    

    And don't forget to put the C# code to:

    private void button1_Click(object sender, RoutedEventArgs e) {}
    

    You can use MediaElement as well but you have to define a VideoClip to see something ;)

提交回复
热议问题