我使用触摸手势在canvas元素中移动并缩放矩形。该代码基于以下引用:http://msdn.microsoft.com/en-us/magazine/gg650664.aspx
XAML代码如下:
<Canvas Name="canvas" >
<Rectangle x:Name="rectangle" Fill="Green" Height="300" Canvas.Left="0" Stroke="Red" Canvas.Top="0" Width="100" StrokeThickness="3" >
<Rectangle.RenderTransform>
<TransformGroup>
<MatrixTransform x:Name="previousTransform" />
<TransformGroup x:Name="currentTransform">
<ScaleTransform x:Name="scaleTransform" />
<TranslateTransform x:Name="translateTransform" />
</TransformGroup>
</TransformGroup>
</Rectangle.RenderTransform>
<toolkit:GestureService.GestureListener>
<toolkit:GestureListener DragStarted="OnGestureListenerDragStarted"
DragDelta="OnGestureListenerDragDelta"
DragCompleted="OnGestureListenerDragCompleted"
PinchStarted="OnGestureListenerPinchStarted"
PinchDelta="OnGestureListenerPinchDelta"
PinchCompleted="OnGestureListenerPinchCompleted" />
</toolkit:GestureService.GestureListener>
</Rectangle>
</Canvas>
Dragging功能:
void OnGestureListenerDragDelta(object sender, DragDeltaGestureEventArgs args)
{
translateTransform.X += args.HorizontalChange;
translateTransform.Y += args.VerticalChange;
}
在捏合期间,比例变换会更新:
void OnGestureListenerPinchDelta(object sender, PinchGestureEventArgs args)
{
scaleTransform.ScaleX = args.DistanceRatio;
scaleTransform.ScaleY = args.DistanceRatio;
}
当捏合完成时,我想得到真实的&#34;父画布中矩形的大小和位置。因此,我尝试将变换应用于矩形边界:
void OnGestureListenerPinchCompleted(object sender, PinchGestureEventArgs args)
{
Rect r = currentTransform.TransformBounds(new Rect(Canvas.GetLeft(rectangle), Canvas.GetTop(rectangle), rectangle.Width, rectangle.Height));
rectangle.Width = r.Width;
rectangle.Height = r.Height;
Canvas.SetLeft(rectangle, r.X);
Canvas.SetTop(rectangle, r.Y);
// Reset transforms
previousTransform.Matrix = new Matrix();
rectangle.RenderTransformOrigin = new Point(0, 0);
scaleTransform.ScaleX = scaleTransform.ScaleY = 1;
scaleTransform.CenterX = scaleTransform.CenterY = 0;
translateTransform.X = translateTransform.Y = 0;
}
这适用于平移,但缩放是错误的(矩形是缩放的,但是在增大比例时因子太大,而在缩小比例时太小)。如何获得缩放矩形的正确最终尺寸?
此致
答案 0 :(得分:0)
我通过省略转换矩阵类并手动使用缩放因子和转换值来解决问题。
尽管如此,我对使用上述XAML代码的解决方案感兴趣。