Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UWP 10 RenderTargetBitmap a cropped area of UIElement in UWP 10

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.

like image 658
MB. Avatar asked Oct 30 '22 08:10

MB.


1 Answers

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.

like image 53
Andrei Ashikhmin Avatar answered Jan 04 '23 14:01

Andrei Ashikhmin