【IT168 专稿】Windows 7带来了许多好的功能,如更好的资源管理器,更好的性能,跳转列表(Jumplist)管理,多点触摸功能等等。这里我将介绍一下使用.Net 3.5 SP1开发一个简单的多点触摸应用程序。
前提条件
首先要下载Windows 7多点触摸API,下载地址http://cid-5c93c05515dfe04a.skydrive.live.com/self.aspx/My%20Blog%20Share/Win7%20MultiTouchAPI.zip,然后解压下载到的压缩包,另外要确定你确实使用的是Windows 7,电脑屏幕也支持多点触摸。
XAML实现
使用Visual Studio 2008创建一个WPF应用程序,将会自动为你创建一个名叫Window1.xaml的XAML文件。然后在解决方案目录下放一张图片,并在XAML文件中插入引用代码,如:
给图片设置RenderTransform属性,以便可以伸缩和旋转它,于是再向XAML文件中增加内容,如下:
当你增加不同的转换类型到转换组时,请使用正确的名称,你在文件后面的代码中要处理它时就很方便了。
运行你的程序,将会打开一个窗口,显示一张图片,如果你试图拖动或旋转图像,你会发现做不了这些操作,因为我们还没有集成这些功能。
代码实现
从解压后的文件夹添加两个项目引用到你的解决方案,如“Windows7.Multitouch”和“Windows7.Multitouch.WPF”,它们是多点触摸应用程序开发需要用到的托管API代码,打开Window1.xaml.cs,确定包括下面的命名空间,如果没有就手动加上。
using System.Windows;
using Windows7.Multitouch;
using Windows7.Multitouch.Manipulation;
using Windows7.Multitouch.WPF;
在你的局部类中创建两个私有成员:
private ManipulationProcessor manipulationProcessor = new ManipulationProcessor(ProcessorManipulations.ALL);
// boolean value to check whether you have a multitouch enabled screen
private static bool IsMultitouchEnabled = TouchHandler.DigitizerCapabilities.IsMultiTouchReady;
接下来插入Window Load事件:
if (IsMultitouchEnabled)
{
// enables stylus events for processor manipulation
Factory.EnableStylusEvents(this);
// add the stylus events
StylusDown += (s, e) =>
{
manipulationProcessor.ProcessDown((uint)e.StylusDevice.Id, e.GetPosition(this).ToDrawingPointF());
};
StylusUp += (s, e) =>
{
manipulationProcessor.ProcessUp((uint)e.StylusDevice.Id, e.GetPosition(this).ToDrawingPointF());
};
StylusMove += (s, e) =>
{
manipulationProcessor.ProcessMove((uint)e.StylusDevice.Id, e.GetPosition(this).ToDrawingPointF());
};
// register the ManipulationDelta event with the manipulation processor
manipulationProcessor.ManipulationDelta += ProcessManipulationDelta;
// set the rotation angle for single finger manipulation
manipulationProcessor.PivotRadius = 2;
}
在事件处理程序块部分编写你的逻辑,我这里实现了旋转,缩放和图像定位功能,代码如下:
{
trTranslate.X += e.TranslationDelta.Width;
trTranslate.Y += e.TranslationDelta.Height;
trRotate.Angle += e.RotationDelta * 180 / Math.PI;
trScale.ScaleX *= e.ScaleDelta;
trScale.ScaleY *= e.ScaleDelta;
}
小结
从ManipulationDeltaEventArgs你可以得到不同的值,根据这些值你可以在这个块中实现你自己的功能,TranslateTransform实现图像定位,RotateTransform实现图像旋转,ScaleTransform调整图像的大小。现在可以运行你的项目,测试你的第一个多点触摸应用程序。
原文名:Windows 7 Multitouch Application Development (Part - I)