WPF图像裁剪

时间:2016-08-19 20:10:18

标签: c# wpf image crop

我的图像裁剪有问题。当我尝试使用矩形裁剪图像时,裁剪区域设置为某个奇怪的值。 这是xaml代码:

   <Grid Name="GridImage">
        <Image Name="LoadedImage" SnapsToDevicePixels="True" RenderOptions.BitmapScalingMode="HighQuality">
        </Image>
        <Canvas  x:Name="ImageCanvas" ClipToBounds="True">
            <Rectangle x:Name="SelectionRectangle" Stroke="LightBlue" Fill="#220000FF" Visibility="Collapsed" />
        </Canvas>
  </Grid>

以及我如何裁剪图片:

            var imagePosition = LoadedImage.TransformToAncestor(GridImage).Transform(new Point(0, 0));
            Rect rect1 = new Rect(Math.Max(Canvas.GetLeft(SelectionRectangle) - imagePosition.X, 0), Math.Max(Canvas.GetTop(SelectionRectangle) - imagePosition.Y, 0), SelectionRectangle.Width, SelectionRectangle.Height);
            var ratioX = LoadedImage.Source.Width / LoadedImage.ActualWidth;
            var ratioY = LoadedImage.Source.Height / LoadedImage.ActualHeight;


            Int32Rect rcFrom = new Int32Rect
            {
                X = (int)(rect1.X * ratioX),
                Y = (int)(rect1.Y * ratioY),
                Width = (int)(rect1.Width * ratioX),
                Height = (int)(rect1.Height * ratioY)
            };
            try
            {
                BitmapSource bs = new CroppedBitmap((BitmapSource)LoadedImage.Source, rcFrom);
                LoadedImage.Source = bs;
                SetImageStretch(LoadedImage);
                SetElementVisibility(Visibility.Hidden, Visibility.Visible, SelectionRectangle);
            }


    private void SetImageStretch(Image image)
    {
        if (image.Source.Width > image.ActualWidth || image.Source.Height > image.ActualHeight)
            image.Stretch = Stretch.Uniform;
        else image.Stretch = Stretch.None;
    }

有人知道如何解决这个问题吗?

这是裁剪前的样子:

enter image description here

裁剪后如何看待:

enter image description here

1 个答案:

答案 0 :(得分:1)

最有可能的问题是图像分辨率,例如300 dpi,相对于屏幕分辨率(最可能是96 dpi)。你有没有检查过图像的PixelWidth和PixelHeight?