将画布缩放到鼠标位置 [英] Scale canvas to mouse position

查看:27
本文介绍了将画布缩放到鼠标位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用鼠标滚轮为画布实现缩放功能.目前我只是使用 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 财产

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;
}

这篇关于将画布缩放到鼠标位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆