开发者

How to copy some part of WriteableBitmap?

开发者 https://www.devze.com 2023-03-08 04:59 出处:网络
I have some WriteableBitmap object. Lets say that the image that is actully on the WriteableBitmap object is 600x400.

I have some WriteableBitmap object. Lets say that the image that is actully on the WriteableBitmap object is 600x400.

I want to copy part of the image - some Rectangle ( for example Rectangle of 100x100 in the middle of the WriteableBitmap ) and paste t开发者_如何转开发he copy to some other image control.

How can i do it ?


I suspect you've got this fixed now, but I had the same problem and I found the answer so I thought I'd post it. The code at http://writeablebitmapex.codeplex.com/ has a "Crop" routine that does pretty much what you're after. Once you have a SizeOfArgb constant set to 4, you can use this:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号