I'm trying to automatically create a photo collage with Win2D library. I've defined a couple of methods to do that:
ICanvasImage RotateImage(ICanvasImage photo, Size size, float degrees) returns a rotated image. I need to pass the image, its size and the degrees number. This method works for other things so I don't think it's that the problem.
ICanvasImage AddImage(ICanvasImage image, Size size, float x, float y, float degrees) it's the guilty. It draws the image on a CanvasRenderTarget with the specified position and size. It first call RotateImage to get the photo with the correct rotation and then draw it on the canvas.
At the end I use a method to save the content of the canvas as an image but it's not important, it works...
If I draw an horizontal image (no rotation => 0 degrees) I have no problem because the destination rectangle to pass to renderer.drawImage() is perfectly align with the photo. If I specified any angle the the image comes rotated correctly but the destination rectangle keeps horizontal an then the photo get cropped where it's out of the bounds of the rectangle.
This is my code:
//photo => photo to rotate
//size => size of the photo
//degrees => degrees to rotate the photo
ICanvasImage RotateImage(ICanvasImage photo, Size size, float degrees)
{
double height = Math.Sqrt(size.Width * size.Width + size.Height*size.Height);
//convert degreese to radians
float radians = (float)(degrees * Math.PI / 180d);
//get x,y where to place the rotated image
float y = (float)((height - size.Height) / 2.0f);
float x = (float)((height - size.Width) / 2.0f);
Vector2 endpoint = new Vector2((float)size.Width / 2, (float)size.Height / 2);
ICanvasImage image = new Transform2DEffect
{
Source = photo,
TransformMatrix = Matrix3x2.CreateRotation(radians, endpoint)
};
return image;
}
//size => final size that I want to have
//x,y => position of the photo
ICanvasImage AddImage(ICanvasImage image, Size size, float x, float y, float degrees)
{
//get the rotated image
ICanvasImage rotatedImage = RotateImage(image, size, degrees);
//start to draw in the canvas
using (var ds = renderer.CreateDrawingSession())
{
//destination rectangle with the specified position and size
Rect destRect = new Rect(x,y,size.Width,size.Height);
//source rectangle of the photo
Rect sourceRect = new Rect(0,0,rotatedImage.GetBounds(renderer).Width,rotatedImage.GetBounds(renderer).Height);
//draw the image on the canvas
ds.DrawImage(rotatedImage,destRect, sourceRect);
}
//here I call the method to save canvas' content as an image...
//you can simply try drawing directly on a canvasControl
}