5

How does one crop a RenderTargetBitmap? The equivalent of:

    RenderTargetBitmap bmp = new RenderTargetBitmap();
    await bmp.RenderAsync(element , cropRect );

This question seems simple enough, yet there seems to be no real way of doing it. The above semantically sums up my usage case. I want to render part of a Xaml tree. It's a perfectly legit use case.

Saving to a file, which seems to be the most common way of cropping, is really not a good answer. Sure, maybe one day I will save a cropped image into my media library, but not today.

MB.
  • 1,303
  • 12
  • 19

1 Answers1

2

There are BitmapTransform and BitmapDecoder classes, which among other functions allow you to crop images. But I failed to make them work with RenderTargetBitmap, each time bumping on HRESULT: 0x88982F50 exception when trying to pass pixel data from one source to another.

As for different approach, I can think of bringing big guns and implementing it with Win2D. It might not be the most convenient solution, but it does work:

var renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(element, width, height);
var pixels = await renderTargetBitmap.GetPixelsAsync();

var currentDpi = DisplayInformation.GetForCurrentView().LogicalDpi;
var device = CanvasDevice.GetSharedDevice();
var imageSource = new CanvasImageSource(device, width, height, currentDpi);

using (var drawingSession = imageSource.CreateDrawingSession(Colors.Transparent))
using (var bitmap = CanvasBitmap.CreateFromBytes(
    drawingSession, pixels.ToArray(), width, height,
    DirectXPixelFormat.B8G8R8A8UIntNormalized, drawingSession.Dpi))
{
    var cropEffect = new CropEffect
    {
        Source = bitmap,
        SourceRectangle = cropRect,
    };

    drawingSession.DrawImage(cropEffect);
}

ResultImage.Source = imageSource;

Note that I'm not Win2D expret and someone more knowledgeable might want to make corrections to this code.

Community
  • 1
  • 1
Andrei Ashikhmin
  • 2,401
  • 2
  • 20
  • 34
  • I know what path you've taken, because I have gone through the exact same problems. I'm currently relying on Win2D as well, but I think it's very much a hack. Thanks for taking the time to try it out though. – MB. Mar 08 '16 at 12:38