C#实现图像以中心点任意角度旋转
C#中 GDI+ 实现图像围绕中心点旋转任意角度的方法类
Image自带RotateFlip处理方法可以做到简单的90°、180°等角度的旋转或者翻转,但并没有提供操作具体设置角度的方法,这还不算麻烦的 最主要的是Graphics的旋转和翻转都是以左上角为原点,这点就很难受了。
以下提供一个围绕图片中心进行旋转任意角的的方法
/// <summary>
/// 图片旋转
/// </summary>
/// <param name="AngleValue"></param>
/// <returns></returns>
public static Bitmap Rotate(this Bitmap ImageOriginal, float AngleValue)
{
AngleValue = AngleValue % 360;
double radian = AngleValue * Math.PI / 180.0;
double cos = Math.Cos(radian);
double sin = Math.Sin(radian);
int w = ImageOriginal.Width;
int h = ImageOriginal.Height;
int W = (int)(Math.Max(Math.Abs(w * cos - h * sin), Math.Abs(w * cos + h * sin)));
int H = (int)(Math.Max(Math.Abs(w * sin - h * cos), Math.Abs(w * sin + h * cos)));
Bitmap ImageBaseOriginal = new Bitmap(W, H, PixelFormat.Format24bppRgb);
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(ImageBaseOriginal);
g.InterpolationMode = InterpolationMode.NearestNeighbor;
g.SmoothingMode = SmoothingMode.HighQuality;
Point Offset = new Point((W - w) / 2, (H - h) / 2);
Rectangle rect = new Rectangle(Offset.X, Offset.Y, w, h);
Point center = new Point(rect.X + rect.Width / 2, rect.Y + rect.Height / 2);
g.Clear(Color.Transparent);
g.TranslateTransform(center.X, center.Y);
g.RotateTransform(360 - AngleValue);
g.TranslateTransform(-center.X, -center.Y);
g.DrawImage(ImageOriginal, rect);
g.ResetTransform();
g.Save();
g.Dispose();
return ImageBaseOriginal;
}