将画布缩放到鼠标位置
我正在尝试使用鼠标滚轮为画布实现缩放功能.目前我只是使用 CenterX="0.5" 和 CenterY="0.5" 缩放到画布的中心位置.我想更改行为,以便缩放发生在鼠标位置,我想知道这是否可以使用 ScaleTransform.
I am trying to implement a zoom-functionality for a canvas using the mouse wheel. Currently I am just Zooming to the center position of the canvas using CenterX="0.5" and CenterY="0.5". I would like to change the behavior so that the zooming happens at the mouse position and I would like to know if this is possible with a ScaleTransform.
目前我使用以下代码:
<Canvas Width="500" Height="500">
<Canvas.LayoutTransform>
<ScaleTransform CenterX="0.5" CenterY="0.5"
ScaleX="{Binding Zoom}"
ScaleY="{Binding Zoom}" />
</Canvas.LayoutTransform>
</Canvas>
在特定位置缩放 Canvas(或任何其他 UIElement)的一种非常基本的方法是对 RenderTransform
使用 MatrixTransform> 财产
A very basic approach to zoom a Canvas (or any other UIElement) at a specific position would be to use a MatrixTransform for the RenderTransform
property
<Canvas Width="500" Height="500" MouseWheel="Canvas_MouseWheel">
<Canvas.RenderTransform>
<MatrixTransform/>
</Canvas.RenderTransform>
</Canvas>
并更新变换的 Matrix
属性,就像在这个 MouseWheel 处理程序中一样:
and update the Matrix
property of the transform like in this MouseWheel handler:
private void Canvas_MouseWheel(object sender, MouseWheelEventArgs e)
{
var element = (UIElement)sender;
var position = e.GetPosition(element);
var transform = (MatrixTransform)element.RenderTransform;
var matrix = transform.Matrix;
var scale = e.Delta >= 0 ? 1.1 : (1.0 / 1.1); // choose appropriate scaling factor
matrix.ScaleAtPrepend(scale, scale, position.X, position.Y);
transform.Matrix = matrix;
}