如何复制WriteableBitmap的某些部分?

时间:2011-05-23 11:56:26

标签: silverlight

我有一些WriteableBitmap对象。 可以说,WriteableBitmap对象上的图像是600x400。

我想复制部分图像 - 一些Rectangle(例如WriteableBitmap中间的100x100的Rectangle)并将副本粘贴到其他图像控件。

我该怎么办?

2 个答案:

答案 0 :(得分:4)

我怀疑你现在已经解决了这个问题,但我遇到了同样的问题,我找到了答案,所以我想我会发布它。 http://writeablebitmapex.codeplex.com/处的代码有一个“裁剪”例程,可以完成你所追求的任务。将SizeOfArgb常量设置为4后,可以使用:

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;
      }

答案 1 :(得分:1)

    public static BitmapSource Crop(this BitmapSource bmp, Int32Rect rect)
    {
        return new CroppedBitmap(bmp, rect);
    }
相关问题