How to crop a rotated portion of a WriteableBitmap in Windows Store app and C#

2k views Asked by At

In a Windows Store app I want to crop a rotated rectangle part of a WriteableBitmap like Case 2 in the following image.

Image

  • I have P0, Width, Height and P1 and rotation angle of the rectangle.
  • Rotation is based on center of each rectangle

I am using Crop extension method available in WriteableBitmapEx.WinRT for Cropping.

In Case 1 I am doing these:

            RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
            await renderTargetBitmap.RenderAsync(PhotoGrid);

            WriteableBitmap bitmapImage = new WriteableBitmap(renderTargetBitmap.PixelWidth, renderTargetBitmap.PixelHeight);

            IBuffer pixelBuffer = await renderTargetBitmap.GetPixelsAsync();
            using (var stream = new InMemoryRandomAccessStream())
            {
                var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);
                encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)renderTargetBitmap.PixelWidth, (uint)renderTargetBitmap.PixelHeight, 96, 96, pixelBuffer.ToArray());

                await encoder.FlushAsync();
                stream.Seek(0);

                bitmapImage.SetSource(stream);
            }

            // Redraw the WriteableBitmap
            bitmapImage.Invalidate();

            SampleImage.Source = bitmapImage.Crop(new Rect(p0.X, p0.Y, width, height));

But when rotation come in place I don't know what calculation should be applied do to crop like case 2.

Would any of you be kind enough to assist?

Thanks!

1

There are 1 answers

3
Olivier Payen On

The WriteableBitmapEx library implements the RotateFree method.

bitmapImage.RotateFree(70);

http://writeablebitmapex.codeplex.com/SourceControl/changeset/82055