用WPF实现一个简单的图片查看器

今天做一个小工具的时候,需要用到一个简单的图片查看功能,只是想做到到类似Windows中自带的图片查看器那样的支持拖动和缩放即可。由于WPF支持平移和缩放变换,实现这样的功能还是比较简单的。网上搜了一下,发现大部分的代码虽然能实现平移和缩放的功能,但大多做不到类似图片查看器那样的缩放时保持鼠标所在位置不变,用起来很不方便。这里就把我的实现记录下来,以便后续检索。

首先是XAML部分:

    <Grid x:Name="root">
        <Image x:Name="img" Source="2.jpg" MouseWheel="Image_MouseWheel" MouseLeftButtonDown="Image_MouseLeftButtonDown"
                MouseMove="Image_MouseMove" >
            <Image.RenderTransform>
                <TransformGroup>
                    <TranslateTransform x:Name="translate" />
                    <ScaleTransform x:Name="transform" />
                </TransformGroup>
            </Image.RenderTransform>
        </Image>
    </Grid>

然后是后台的处理代码部分:

    private void Image_MouseWheel(object sender, MouseWheelEventArgs e)
    {
        var mosePos = e.GetPosition(img);

        var scale = transform.ScaleX * (e.Delta > 0 ? 1.2 : 1 / 1.2);
        scale = Math.Max(scale, 1);

        transform.ScaleX = scale;
        transform.ScaleY = scale;

        if(scale == 1)        //
缩放率为1的时候,复位
        {
            translate.X = 0;
            translate.Y = 0;
        }
        else                //
保持鼠标相对图片位置不变
        {
            var newPos = e.GetPosition(img);

            translate.X += (newPos.X - mosePos.X);
            translate.Y += (newPos.Y - mosePos.Y);
        }
    }

    Point dragStart;
    private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        dragStart = e.GetPosition(root);
    }

    private void Image_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.LeftButton != MouseButtonState.Pressed)
        {
            return;
        }

        var current = e.GetPosition(root);

        translate.X += (current.X - dragStart.X)/ transform.ScaleX;
        translate.Y += (current.Y - dragStart.Y)/ transform.ScaleY;

        dragStart = current;
    }

代码比较简单,基本上复制过去就能用,这里就不做更多介绍了。

你可能感兴趣的:(WPF)