我有一些WriteableBitmap对象。假设实际上在WriteableBitmap对象上的图像大小为600x400。
我想复制图像的一部分 - 例如WriteableBitmap中间的100x100矩形,并将副本粘贴到其他图像控件中。
我该如何做?
我有一些WriteableBitmap对象。假设实际上在WriteableBitmap对象上的图像大小为600x400。
我想复制图像的一部分 - 例如WriteableBitmap中间的100x100矩形,并将副本粘贴到其他图像控件中。
我该如何做?
我猜您现在已经解决了这个问题,但我遇到了相同的问题并找到了答案,所以我想发布一下。 在http://writeablebitmapex.codeplex.com/网站上的代码有一个“Crop”例程,可以完成您需要的几乎所有操作。一旦您设置了一个值为4的SizeOfArgb常量,就可以使用以下代码:
public static WriteableBitmap Crop(this WriteableBitmap bmp, int x, int y, int width, int height)
{
var srcWidth = bmp.PixelWidth;
var srcHeight = bmp.PixelHeight;
// If the rectangle is completly out of the bitmap
if (x > srcWidth || y > srcHeight)
{
return new WriteableBitmap(0, 0);
}
// Clamp to boundaries
if (x < 0) x = 0;
if (x + width > srcWidth) width = srcWidth - x;
if (y < 0) y = 0;
if (y + height > srcHeight) height = srcHeight - y;
// Copy the pixels line by line using fast BlockCopy
var result = new WriteableBitmap(width, height);
for (var line = 0; line < height; line++)
{
var srcOff = ((y + line) * srcWidth + x) * SizeOfArgb;
var dstOff = line * width * SizeOfArgb;
Buffer.BlockCopy(bmp.Pixels, srcOff, result.Pixels, dstOff, width * SizeOfArgb);
}
return result;
}
public static BitmapSource Crop(this BitmapSource bmp, Int32Rect rect)
{
return new CroppedBitmap(bmp, rect);
}