WPF 之Belling’s 课堂(3 ) 让物体动起来(运用CompositionTarget)(二)
上一个例子实现鼠标点击哪里矩形就用规定的时间跑到那里。无论距离长与否,都用相同的时间到达指点地点。
本例子实现的功能:
点击canvas的某一处,矩形按规定速度移动,无论长度是长是短。
前台UI设计:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <Window x:Class="WPF应用程序1.MainWindow" 2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 4 Title="MainWindow" Height="350" Width="525"> 5 <Canvas x:Name="Carria" Width="470" Height="297" Background="Blue" MouseLeftButtonDown="Carria_MouseLeftButtonDown"></Canvas> 6 7 8 </Window>
后台cs设计:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Windows; 6 using System.Windows.Controls; 7 using System.Windows.Data; 8 using System.Windows.Documents; 9 using System.Windows.Input; 10 using System.Windows.Media; 11 using System.Windows.Media.Imaging; 12 using System.Windows.Navigation; 13 using System.Windows.Shapes; 14 using System.Windows.Media.Animation; 15 16 namespace WPF应用程序1 17 { 18 /// <summary> 19 /// MainWindow.xaml 的交互逻辑 20 /// </summary> 21 public partial class MainWindow : Window 22 { 23 Rectangle rect; //创建一个方块作为演示对象 24 double speed = 1;//设置移动速度 25 Point moveTo; //设置移动目标点 26 27 public MainWindow() 28 { 29 InitializeComponent(); 30 31 //MessageBox.Show("zgz"); 32 rect = new Rectangle(); 33 rect.Fill = new SolidColorBrush(Colors.Bisque); 34 rect.Width = 50; 35 rect.Height = 50; 36 rect.RadiusX = 5; 37 rect.RadiusY = 5; 38 39 Carria.Children.Add(rect); //在canvas(名字是Carria)中加载上rect矩形。 40 41 Canvas.SetLeft(rect, 100);//定位子元素相对canvas的位置 42 Canvas.SetTop(rect, 100); 43 //MessageBox.Show("zgz"); 44 //注册刷新界面,CompositionTarget表示您的应用程序的显示图面。 45 CompositionTarget.Rendering += new EventHandler(Timer_Tick); 46 } 47 private void Carria_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) 48 { 49 moveTo=e.GetPosition(Carria);//获得鼠标在canvas点击处的坐标。。。。 50 } 51 52 private void Timer_Tick(object sender, EventArgs e) 53 { 54 double rect_X = Canvas.GetLeft(rect); //首先获得rect的相对于canvas的位置 55 double rect_Y = Canvas.GetTop(rect); 56 Canvas.SetLeft(rect,rect_X+(rect_X<moveTo.X?speed:-speed));//此处将速度转换为移动到的小单位距离 57 Canvas.SetTop(rect, rect_Y+(rect_Y<moveTo.Y?speed:-speed)); 58 } 59 60 61 62 } 63 }