微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

WPF——对控件进行缩放

对控件进行缩放

控件的缩放属于 Transform, 而对于需要以鼠标位置为中心进行缩放则为 MatrixTransform, 为保证 MVVM 的一致性,采用 System.Windows.Interactivity 中的 Behavior 实现, 下面为实现控件缩放的方法.

StackOverflow: WPF Zoom Canvas Center on Mouse Position

ZoomOnMouseWheel.cs

using System.Windows;
using System.Windows.Input;
using System.Windows.Interactivity;
using System.Windows.Media;

namespace Demo.Utils
{
    public class ZoomOnMouseWheel : Behavior<FrameworkElement>
    {
        public Key? ModifierKey { get; set; } = null;
        public TransformMode TranformMode { get; set; } = TransformMode.Render;

        private Transform _transform;

        protected override void OnAttached()
        {
            if (TranformMode == TransformMode.Render)
            {
                _transform = Associatedobject.RenderTransform = new MatrixTransform();
            }
            else
            {
                _transform = Associatedobject.LayoutTransform = new MatrixTransform();
            }

            Associatedobject.MouseWheel += Associatedobject_MouseWheel;
        }

        protected override void OnDetaching()
        {
            Associatedobject.MouseWheel -= Associatedobject_MouseWheel;
        }

        private void Associatedobject_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            if ((!ModifierKey.HasValue || !Keyboard.IsKeyDown(ModifierKey.Value)) && ModifierKey.HasValue)
            {
                return;
            }

            if (!(_transform is MatrixTransform transform))
            {
                return;
            }

            var pos1 = e.GetPosition(Associatedobject);
            var scale = e.Delta > 0 ? 1.1 : 1 / 1.1;
            var mat = transform.Matrix;
            mat.ScaleAt(scale, scale, pos1.X, pos1.Y);
            transform.Matrix = mat;
            e.Handled = true;
        }
    }

    public enum TransformMode
    {
        Layout,
        Render,
    }
}

View.xaml

<UserControl ...
    xmlns:interactivity="http://schemas.microsoft.com/expression/2010/interactivity"
    xmlns:local="clr-namespace:Demo.Utils">

    <Canvas>
        <interactivity:Interaction.Behaviors>
            <local:ZoomOnMouseWheel ModifierKey="LeftCtrl" TransformMode="Layout">
        </interactivity:Interaction.Behaviors>
    </Canvas>
</UserControl>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐