C # - Rotating and Centering an Image
I have an image that I want to rotate clockwise by a specified number of degrees. I don't want to crop anything, so I calculate the width and height of the new image based on the specified rotation (for example, a 45 degree rotation requires a taller and wider image.
//Calculate required size of new image
GraphicsPath path = new GraphicsPath();
path.AddRectangle(new RectangleF(0f, 0f, bmpSource.Width, bmpSource.Height));
Matrix matrix = new Matrix();
matrix.Rotate(iRotationDegrees);
RectangleF rctNewSize = path.GetBounds(matrix);
//Create new image
Bitmap bmpRotated = new Bitmap(Convert.ToInt32(rctNewSize.Width), Convert.ToInt32(rctNewSize.Height));
using (Graphics g = Graphics.FromImage(bmpRotated))
{
//Set rotation point to center of image
g.TranslateTransform(bmpRotated.Width / 2, 0);
g.RotateTransform(iRotationDegrees);
//Draw the rotated image on the bitmap
g.DrawImageUnscaled(bmpSource, 0,0);
}
With a 45 degree angle, when I set the TranslateTransform to bmpRotated.Width / 2,0, the rotated image is not quite horizontally centered, and the bottom left corner is slightly cut off.
I am missing some math that correctly calculates the appropriate dx / dy values to go to TranslateTransform.
+3
source to share
No one has answered this question yet
Check out similar questions: