手指之舞(二):GestureListener。手势监听操作

来源:互联网 发布:知乎一句话介绍要求 编辑:程序博客网 时间:2024/05/16 00:42

寻找能简单处理触摸事件的方法,silverlight低级触摸屏事件,由于不太方便,暂时不用,高级事件Manipulation。由于没有发现多点触摸处理的方法也果断弃之。接着就发现了Toolkit的GestureListener。用了下,挺方便的。

GestureListener有下面的事件:


如上图,事件基本和名字所述,这里和Manipulation的方法差不多的是GestureBegin,GestureCompleted。DragDelta.DragStarted.DragCompleted.那随便用这个GestureListener小试一把吧。

大家如果玩过WP7的实况就知道。那个控制方向的东东,一个小圆盘。我打算用这个GestureListener来实现下那个。

要添加需要的DLL和命名空间。但是我懒,因为还得到C盘去寻找toolkit的DLL。索性拖控件一把。这样,神马DLL,命名空间都给我添加好了。人懒了没办法。

在XAML下添加如下代码:

<Ellipse x:Name="outside" Width="200" Height="200" HorizontalAlignment="Left"                     VerticalAlignment="Top" Margin="50,50,0,0" Fill="Orange" >            </Ellipse>            <Ellipse x:Name="rectangle" Width="100" Height="100" HorizontalAlignment="Left"                       VerticalAlignment="Top" Margin="100,100,0,0"                            Fill="Blue" Stroke="Red" StrokeThickness="5">                <toolkit:GestureService.GestureListener>                    <toolkit:GestureListener                                              DragDelta="GestureListener_DragDelta"                                             DragCompleted="GestureListener_DragCompleted"                                             />                </toolkit:GestureService.GestureListener>                <Ellipse.RenderTransform>                    <TranslateTransform x:Name="translation"/>                </Ellipse.RenderTransform>            </Ellipse>  

在设计器上显示如下:


现在思路是:主要处理触摸操作在里面的圆。使之可以在外圆里面动,那么要做的只是在Delta下控制内圆的位置和DragCompleted下把内圆放回原处。感觉不错的是DragDeltaGestureEventArgs提供了平行和竖直方向的坐标改变值。这样做起来就相当方便了。

那么代码如下:

      private void GestureListener_DragDelta(object sender, DragDeltaGestureEventArgs e)        {            double x = this.translation.X + e.HorizontalChange;            double y = this.translation.Y + e.VerticalChange;            if (x <= -50)                this.translation.X = -50;            else if (x >= 50)                this.translation.X = 50;            else                this.translation.X = x;            if (y <= -50)                this.translation.Y = -50;            else if (y >= 50)                this.translation.Y = 50;            else                this.translation.Y = y;        }        private void GestureListener_DragCompleted(object sender, DragCompletedGestureEventArgs e)        {            this.translation.X = 0;            this.translation.Y = 0;        }  

这样,就可以实现内圆在外圆上运动了。如果想要知道究竟现在手指控制的方向是上下左右什么的。自己判断translation的坐标就知道了。这个TranslateTransform提供的是左上角的坐标并且相对自己为(0,0)。很好处理吧。


不过,可惜的是,这个GestureListener也是用的是主要触摸点,如果是非主要触摸点它又不工作了。。。。可惜了。不过做些手势操作识别还是很不错的选择。