潘&缩放图像 [英] Pan & Zoom Image

查看:21
本文介绍了潘&缩放图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 WPF 中创建一个简单的图像查看器,使用户能够:

I want to create a simple image viewer in WPF that will enable the user to:

  • 平移(通过鼠标拖动图像).
  • 缩放(使用滑块).
  • 显示叠加层(例如矩形选择).
  • 显示原始图像(如果需要,带有滚动条).

你能解释一下怎么做吗?

Can you explain how to do it?

我在网上没有找到好的样本.我应该使用 ViewBox 吗?还是ImageBrush?我需要滚动查看器吗?

I didn't find a good sample on the web. Should I use ViewBox? Or ImageBrush? Do I need ScrollViewer?

推荐答案

我解决这个问题的方法是将图像放置在一个 Border 中,并将它的 ClipToBounds 属性设置为 True.然后将图像上的 RenderTransformOrigin 设置为 0.5,0.5,这样图像将开始在图像中心缩放.RenderTransform 也设置为包含 ScaleTransform 和 TranslateTransform 的 TransformGroup.

The way I solved this problem was to place the image within a Border with it's ClipToBounds property set to True. The RenderTransformOrigin on the image is then set to 0.5,0.5 so the image will start zooming on the center of the image. The RenderTransform is also set to a TransformGroup containing a ScaleTransform and a TranslateTransform.

然后我处理了图片上的MouseWheel事件来实现缩放

I then handled the MouseWheel event on the image to implement zooming

private void image_MouseWheel(object sender, MouseWheelEventArgs e)
{
    var st = (ScaleTransform)image.RenderTransform;
    double zoom = e.Delta > 0 ? .2 : -.2;
    st.ScaleX += zoom;
    st.ScaleY += zoom;
}

为了处理平移,我做的第一件事是处理图像上的 MouseLeftButtonDown 事件,捕捉鼠标并记录它的位置,我还存储 TranslateTransform 的当前值,这是更新以实现平移.

To handle the panning the first thing I did was to handle the MouseLeftButtonDown event on the image, to capture the mouse and to record it's location, I also store the current value of the TranslateTransform, this what is updated to implement panning.

Point start;
Point origin;
private void image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    image.CaptureMouse();
    var tt = (TranslateTransform)((TransformGroup)image.RenderTransform)
        .Children.First(tr => tr is TranslateTransform);
    start = e.GetPosition(border);
    origin = new Point(tt.X, tt.Y);
}

然后我处理了 MouseMove 事件以更新 TranslateTransform.

Then I handled the MouseMove event to update the TranslateTransform.

private void image_MouseMove(object sender, MouseEventArgs e)
{
    if (image.IsMouseCaptured)
    {
        var tt = (TranslateTransform)((TransformGroup)image.RenderTransform)
            .Children.First(tr => tr is TranslateTransform);
        Vector v = start - e.GetPosition(border);
        tt.X = origin.X - v.X;
        tt.Y = origin.Y - v.Y;
    }
}

最后不要忘记释放鼠标捕获.

Finally don't forget to release the mouse capture.

private void image_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    image.ReleaseMouseCapture();
}

至于调整大小的选择句柄可以使用装饰器完成,请查看 这篇文章了解更多信息.

As for the selection handles for resizing this can be accomplished using an adorner, check out this article for more information.

这篇关于潘&缩放图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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