欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Wpf一个简单的物体移动动画

程序员文章站 2022-06-20 15:14:00
[html]

[html]
<window x:class="wpfdemo1.mainwindow" 
        xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml" 
        title="mainwindow" height="350" width="525" loaded="window_loaded" mouseleftbuttondown="window_mouseleftbuttondown"> 
    <canvas x:name="body"> 
         
         
         
    </canvas> 
</window> 

[csharp] 
/// <summary> 
    /// mainwindow.xaml 的交互逻辑 
    /// </summary> 
    public partial class mainwindow : window 
    { 
        ellipse ell; 
 
        public mainwindow() 
        { 
            initializecomponent(); 
 
            ell = new ellipse(); 
 
            ell.fill = new solidcolorbrush(colors.red); 
            ell.width = 50; 
            ell.height = 50; 
 
            body.children.add(ell); 
 
            canvas.setleft(ell, 100); 
            canvas.settop(ell,100); 
 
        } 
 
        private void window_loaded(object sender, routedeventargs e) 
        { 
             
        } 
 
        private void window_mouseleftbuttondown(object sender, mousebuttoneventargs e) 
        { 
            moveto(e.getposition(body)); 
        } 
 
 
        private void moveto(point deskpoint) 
        { 
            //point p = e.getposition(body); 
 
            point curpoint = new point(); 
            curpoint.x = canvas.getleft(ell); 
            curpoint.y = canvas.gettop(ell); 
 
            double _s = system.math.sqrt(math.pow((deskpoint.x - curpoint.x), 2) + math.pow((deskpoint.y - curpoint.y), 2)); 
 
            double _secnumber = (_s / 1000) * 500; 
 
            storyboard storyboard = new storyboard(); 
 
            //创建x轴方向动画 
 
            doubleanimation doubleanimation = new doubleanimation( 
 
              canvas.getleft(ell), 
 
              deskpoint.x, 
 
              new duration(timespan.frommilliseconds(_secnumber)) 
 
            ); 
            storyboard.settarget(doubleanimation, ell); 
            storyboard.settargetproperty(doubleanimation, new propertypath("(canvas.left)")); 
            storyboard.children.add(doubleanimation); 
 
            //创建y轴方向动画 
 
            doubleanimation = new doubleanimation( 
              canvas.gettop(ell), 
              deskpoint.y, 
              new duration(timespan.frommilliseconds(_secnumber)) 
            ); 
            storyboard.settarget(doubleanimation, ell); 
            storyboard.settargetproperty(doubleanimation, new propertypath("(canvas.top)")); 
            storyboard.children.add(doubleanimation); 
 
 
 
            //动画播放 
 
            storyboard.begin(); 
        } 
    } 

通过动画析storyboard实现元素移动功能。