• Canvas没有添加Background,点击就不在Canvas上?


    看过深蓝色右手 的WPF/Silverlight动画游戏教程之让物体动起来,利用CompositionTarget.Rendering 来创建动画,自己动手,

    流程如下:

    1. 创建Rectangle对象
    2. 将对象添加至页面并注册鼠标左键事件
    3. 在鼠标单击事件里面计算对象离单击位置的距离,并计算x、y方向分速度
    4. 刷新界面,移动对象,判断对象是否移动到位,若到位取消注册事件

    改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上?

  • 相关阅读:
    2018年11月1日开通博客园感想!
    Aspnet MVC 异步调用
    AspNet WebApi : MessageHandler(消息处理器 )
    AspNet MVC : 操作/控制器过滤器(action filter)
    PHP 面向对对象基础(接口,类)
    原生Ajax + Promise
    基于Qt QGraphicsView的多点触摸绘图
    node应用通过multer模块实现文件上传
    AspNet WebApi: 了解下HttpControllerDispatcher,控制器的创建和执行
    视频投影(二维视频投影到三维模型上)
  • 原文地址:https://www.cnblogs.com/ITBread/p/2221234.html
Copyright © 2020-2023  润新知