重庆网站房地产,伪春菜wordpress,2021网络营销成功案例,龙采哈尔滨建站公司【 声明#xff1a;版权所有#xff0c;欢迎转载#xff0c;请勿用于商业用途。 联系信箱#xff1a;feixiaoxing 163.com】 在软件开发中#xff0c;如果存在canvas图像的话#xff0c;一般有几种控制方法。一种是鼠标控制#xff1b;一种是键盘控制#xff1b;还有一…【 声明版权所有欢迎转载请勿用于商业用途。 联系信箱feixiaoxing 163.com】 在软件开发中如果存在canvas图像的话一般有几种控制方法。一种是鼠标控制一种是键盘控制还有一种是定时器控制。定时器控制多常见动画、游戏、3d视频当中。而鼠标控制和键盘控制是更为常见的操作方法。鼠标控制之前绘图已经提到了今天主要说一说键盘的绘图控制。 要实现键盘的绘图控制关键在于有一个反馈回调函数。每当有按键按下去的时候我们可以收到对应的回调接口这样就可以对绘图进行控制了。 1、界面设计 界面设计有两个部分组成一个是显示图形目前是一个三角形模拟一个小飞机。我们对键盘的控制也是为了这个小飞机可以上、下、前、后运动。另外一个就是一个label它显示当前哪个键被按下去了主要也是为了调试使用。初始的时候三角形和label是重合的。 对应的xaml如下所示
Window x:ClassWpfApp.MainWindowxmlnshttp://schemas.microsoft.com/winfx/2006/xaml/presentationxmlns:xhttp://schemas.microsoft.com/winfx/2006/xamlxmlns:dhttp://schemas.microsoft.com/expression/blend/2008xmlns:mchttp://schemas.openxmlformats.org/markup-compatibility/2006xmlns:localclr-namespace:WpfAppmc:IgnorabledTitleMainWindow Height450 Width600 KeyDownWindow_KeyDown FocusableTrueCanvas Namecanvas BackgroundWhitePolygon Nameairplane Points0,0 30,10 0,20 StrokeBlack FillLightBlue /Label x:Namelabel ContentCurrent key: None Margin0,0,0,0//Canvas
/Window在整个xaml文件当中最最重要的就是Window_KeyDown这个回调函数这和之前的MouseDown、MouseMove、MouseUp是很相似的。只不过canvas不支持keydown只好把对应的事件挪到上一层了。 2、代码设计 代码实现最主要的部分就是如何初始化好三角形以及如果响应键盘的操作。初始化的动作肯定是在窗口的构造函数完成的而剩下来的内容就是键盘的操作响应了。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;using System.Threading;namespace WpfApp
{/// summary/// MainWindow.xaml 的交互逻辑/// /summarypublic partial class MainWindow : Window{private double airplaneLeft 0;private double airplaneTop 150;private double airplaneSpeed 5;public MainWindow(){InitializeComponent();UpdateAirplanePosition();}private void Window_KeyDown(object sender, KeyEventArgs e){switch (e.Key){case Key.Left:airplaneLeft - airplaneSpeed;label.Content Current key: left;break;case Key.Right:airplaneLeft airplaneSpeed;label.Content Current key: right;break;case Key.Up:airplaneTop - airplaneSpeed;label.Content Current key: up;break;case Key.Down:airplaneTop airplaneSpeed;label.Content Current key: down;break;}UpdateAirplanePosition();}private void UpdateAirplanePosition(){Canvas.SetLeft(airplane, airplaneLeft);Canvas.SetTop(airplane, airplaneTop);}}}为了确定每一次按键被按下去的时候是不是真的起作用在Window_KeyDown回调函数中增加了label显示的内容。这也算是一种调试的方法和手段吧。 3、测试和验证 测试的方法就非常简单了。编译无误之后利用键盘上的上下左右按键判断下三角形是否可以发生相应的移动并且label打印对不对如果没啥问题的话就说明相关的功能是ok的没有啥问题的。