Canvas没有添加Background,点击就不在Canvas上?
看过深蓝色右手 的WPF/Silverlight动画游戏教程之让物体动起来,利用CompositionTarget.Rendering 来创建动画,自己动手,
流程如下:
- 创建Rectangle对象
- 将对象添加至页面并注册鼠标左键事件
- 在鼠标单击事件里面计算对象离单击位置的距离,并计算x、y方向分速度
- 刷新界面,移动对象,判断对象是否移动到位,若到位取消注册事件
改MainPage.xaml里面的Grid为Canvas去掉Background="White"
<Canvas x:Name="LayoutRoot"/>
bool isRendering = false;
double speed = 10;
double xSpeed, ySpeed;
int num;
int count;
Rectangle rectangle = new Rectangle()
{
Width = 50,
Height = 50,
Fill = new SolidColorBrush() {Color=Colors.Red }};
public MainPage()
{
InitializeComponent();
LayoutRoot.Children.Add(rectangle);
LayoutRoot.MouseLeftButtonDown += new MouseButtonEventHandler(LayoutRoot_MouseLeftButtonDown);
}void LayoutRoot_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Point start = new Point(Canvas.GetLeft(rectangle),Canvas.GetTop(rectangle));
Point end = e.GetPosition(LayoutRoot);//勾股定理
double distance = Math.Sqrt(Math.Pow(end.X - start.X, 2) + Math.Pow(end.Y - start.Y, 2));
num = (int)(distance / speed);//xSpeed ySpeed分别指x、y方向的分速度(高数里面的几何,与向量章节)
xSpeed = (end.X - start.X) * speed / distance;
ySpeed = (end.Y - start.Y) * speed / distance;
count = 0;
if (!isRendering) {
CompositionTarget.Rendering += new EventHandler(CompositionTarget_Rendering);
isRendering = true;
}
}void CompositionTarget_Rendering(object sender, EventArgs e)
{
double x = Canvas.GetLeft(rectangle);
double y = Canvas.GetTop(rectangle);
Canvas.SetLeft(rectangle, x + xSpeed);
Canvas.SetTop(rectangle, y + ySpeed);
if (count == num)
{
CompositionTarget.Rendering -= CompositionTarget_Rendering;
isRendering = false;
}
count++;}
编译,通过没有出错,可鼠标点击就是不灵,要点击对象很近的地方才有用,反复查看代码,未发现问题,回到深蓝色右手博客,查看,只是自己少写几个属性Width="800" Height="600" Background="Silver",当在Canvas后添加Background,编译,居然通过。鼠标点击,即点即到,很灵活,难道没有添加Background,点击就不在Canvas上?