【WPF】对Image元素进行缩放平移等操作

元素布局

        <Border Grid.Row="1" Name="border" ClipToBounds="True" Margin="10,10,10,10">
            <Image Name="image" Visibility="Visible" Margin="3,3,3,3" Grid.Column="1" Source="{Binding SourceImage}" HorizontalAlignment="Center" VerticalAlignment="Center">
            Image>
        Border>

1.平移

1.1 定义私有变量记录相关初始位置

        /// 
        /// 图片的起始偏移位置
        /// 
        private Point origin;  
        /// 
        /// 鼠标相对Border的起始位置
        /// 
        private Point start; 

1.2 绑定 鼠标左键按下鼠标左键抬起鼠标移动事件

        public DialogImageWindow()
        {
            InitializeComponent();
            image.MouseLeftButtonDown += image_MouseLeftButtonDown;
            image.MouseLeftButtonUp += image_MouseLeftButtonUp;
            image.MouseMove += image_MouseMove;
        }

1.3 鼠标左键按下

  1. 通过CaptureMouse将鼠标捕获到指定的元素image
  2. 通过GetPosition获取鼠标相对border位置
  3. 记录image当前偏移位置
        private void image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (image.IsMouseCaptured) return;
            image.CaptureMouse();

            start = e.GetPosition(border);
            origin.X = image.RenderTransform.Value.OffsetX;
            origin.Y = image.RenderTransform.Value.OffsetY;
        }

1.4 鼠标移动

  1. 通过GetPosition获取当前鼠标相对border位置
  2. 计算鼠标相对初始位置移动的像素差值
  3. 将像素差值累计到初始偏移量上
 private void image_MouseMove(object sender, MouseEventArgs e)
        {
            if (!image.IsMouseCaptured) return;
            Point p = e.MouseDevice.GetPosition(border);

            Matrix m = image.RenderTransform.Value;
            m.OffsetX = origin.X + (p.X - start.X);
            m.OffsetY = origin.Y + (p.Y - start.Y);

            image.RenderTransform = new MatrixTransform(m);
        }

1.5 鼠标左键抬起

  1. 通过ReleaseMouseCapture释放鼠标捕获
private void image_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (image.IsMouseCaptured)
            {
                image.ReleaseMouseCapture();
            }
        }

2. 缩放

2.1 绑定 鼠标滚轮事件

        public DialogImageWindow()
        {
            InitializeComponent();
            MouseWheel += MainWindow_MouseWheel;
        }

2.1

  1. 通过GetPosition获取鼠标相对image的位置,该位置作为缩放中心点
  2. 根据Delta参数来决定是在当前放大系数上放大(1.1倍)还是缩小(1.1倍).
 private void MainWindow_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            Point p = e.MouseDevice.GetPosition(image);

            Matrix m = image.RenderTransform.Value;
            if (e.Delta > 0)
                m.ScaleAtPrepend(1.1, 1.1, p.X, p.Y);
            else
                m.ScaleAtPrepend(1 / 1.1, 1 / 1.1, p.X, p.Y);

            image.RenderTransform = new MatrixTransform(m);
        }

3. 还原

private void b1_Click(object sender, RoutedEventArgs e)
        {
            image.RenderTransform = new ScaleTransform(1.0,1.0);
            image.RenderTransform = new TranslateTransform(0,0);
        }

你可能感兴趣的:(语言-CSharp,wpf,Image,ScaleTransform,缩放,平移)