WPF 图像裁剪

WPF Image Cropping

我的图像裁剪有问题。当我尝试用矩形裁剪图像时,裁剪区域被设置为一些奇怪的值。 这是 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;
    }

有人知道如何解决吗?

这是裁剪前的样子:

裁剪后的效果:

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