c#-旋转图像并使其居中

c#-旋转图像并使其居中,c#,.net,bitmap,C#,.net,Bitmap,我有一个图像,我想顺时针旋转指定的度数。我不想剪掉任何东西,所以我根据指定的旋转计算新图像的宽度和高度(例如,旋转45度需要更高更宽的图像) //Calculate required size of new image GraphicsPath path = new GraphicsPath(); path.AddRectangle(new RectangleF(0f, 0f, bmpSource.Width, bmpSource.Height)); Matrix matrix = new Ma

我有一个图像,我想顺时针旋转指定的度数。我不想剪掉任何东西,所以我根据指定的旋转计算新图像的宽度和高度(例如,旋转45度需要更高更宽的图像)

//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); 
}
角度为45度时,当我将TranslateTransform设置为bmpRotated.Width/2,0时,旋转后的图像在水平方向上没有完全居中,左下角被切掉一点


我这里缺少一些数学知识,无法正确计算要传递给TranslateTransform的适当dx/dy值。

您不是从图像中心进行翻译,而是从图像顶部的中心进行翻译。请使用
bmpRotated.Height/2
而不是
0