在 WPF 中裁剪图像

Crop an Image in WPF

给个图:

Image tileSet = new Image();
tileSet.Source = new BitmapImage(new Uri(@".."));

如何裁剪它,定义一个矩形区域?

你可以使用 CroppedBitmap

var fullBitmap = new BitmapImage(new Uri(@".."));
tileSet.Source = new CroppedBitmap(fullBitmap, new Int32Rect(0, 0, 100, 100));

要在 dkozl 上面的回答的基础上做一点,

我发现要裁剪的原始图像的 DPI 和显示器的 DPI 正在创建我打算裁剪原始图像的位置的“偏移”。

可以通过将图像的宽度和高度(以像素为单位)与屏幕的 DPI 相匹配来纠正“偏移”,而不是让图像元素自动调整大小。 为此,您可以将拉伸设置为 None,并将图像的宽度和高度设置为如下所示:

<Image
    x:Name="imageToCrop"
    Stretch="None"
    Width="{Binding Source.PixelWidth,RelativeSource={RelativeSource Self}}"
    Height="{Binding Source.PixelHeight,RelativeSource={RelativeSource Self}}"/>