I need to rotate a WriteableBitmap and scale it down or up before it gets cropped.
My current code will rotate but will crop the edges if the height is larger then the width.
I assume I need to scale?
public WriteableBitmap Rotate(WriteableBitmap Source, double Angle)
{
RotateTransform rt = new RotateTransform();
rt.Angle = Angle;
TransformGroup transform = new TransformGroup();
transform.Children.Add(rt);
Image tempImage2 = new Image();
WriteableBitmap wb;
rt.CenterX = Source.PixelWidth / 2;
rt.CenterY = Source.PixelHeight / 2;
tempImage2.Width = Source.PixelWidth;
tempImage2.Height = Source.PixelHeight;
wb = new WriteableBitmap((int)(Source.PixelWidth), Source.PixelHeight);
tempImage2.Source = Source;
tempImage2.UpdateLayout();
wb.Render(tempImage2, transform);
wb.Invalidate();
return wb;
}
How do I scale down the image so it will not be cropped? Or is there another way?
You need to calculate the scaling based on the rotation of the corners relative to the centre.
If the image is a square only one corner is needed, but for a rectangle you need to check 2 corners in order to see if a vertical or horizontal edge is overlapped. This check is a linear comparison of how much the rectangle's height and width are exceeded.
Click here for the working testbed app created for this answer (image below):
The pseudo-code is as follows (actual C# code at the end):
The result is a multiplier that will scale the image down to fit the original rectangle regardless of rotation.
**Note: While it is possible to do much of the maths using matrix operations, there are not enough calculations to warrant that. I also thought it would make a better example from first-principles.*
C# Code:
Example of use:
I released a Test-bed of the code on my website so you can try it for real - click to try it