元素布局
<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; private Point start;
1.2 绑定 鼠标左键按下
、鼠标左键抬起
、鼠标移动
事件
public DialogImageWindow(){InitializeComponent();image.MouseLeftButtonDown += image_MouseLeftButtonDown;image.MouseLeftButtonUp += image_MouseLeftButtonUp;image.MouseMove += image_MouseMove;}
1.3 鼠标左键按下
- 通过
CaptureMouse
将鼠标捕获到指定的元素image
- 通过
GetPosition
获取鼠标相对border
位置 - 记录
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 鼠标移动
- 通过
GetPosition
获取当前鼠标相对border
位置 - 计算鼠标相对初始位置移动的像素差值
- 将像素差值累计到初始偏移量上
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 鼠标左键抬起
- 通过
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
- 通过
GetPosition
获取鼠标相对image
的位置,该位置作为缩放中心点 - 根据
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);elsem.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);}