Winform以任意角度旋转PictureBox中的图片的方法

时间:2023-03-09 18:52:16
Winform以任意角度旋转PictureBox中的图片的方法

方法1:

  private void RotateFormCenter(PictureBox pb, float angle)
{
Image img = pb.Image;
int newWidth = Math.Max(img.Height, img.Width);
Bitmap bmp = new Bitmap(newWidth, newWidth);
Graphics g = Graphics.FromImage(bmp);
Matrix x = new Matrix();
PointF point = new PointF(img.Width / 2f, img.Height / 2f);
x.RotateAt(angle, point);
g.Transform = x;
g.DrawImage(img, 0, 0);
g.Dispose();
img = bmp;
pb.Image = img;
}

  该方法通过将图片转化为用于几何变换的3x3矩阵 对图片进行旋转。

  缺点:有时图片会越转越模糊。

方法2:

private void RotateFormCenter(PictureBox pb, float angle)
{
Graphics graphics = pb.CreateGraphics();
graphics.Clear(pb.BackColor);
//装入图片
Bitmap image = new Bitmap(pb.Image);
//获取当前窗口的中心点
Rectangle rect = new Rectangle(, , pb.Width, pb.Height);
PointF center = new PointF(rect.Width / , rect.Height / );
float offsetX = ;
float offsetY = ;
offsetX = center.X - image.Width / ;
offsetY = center.Y - image.Height / ;
//构造图片显示区域:让图片的中心点与窗口的中心点一致
RectangleF picRect = new RectangleF(offsetX, offsetY, image.Width, image.Height);
PointF Pcenter = new PointF(picRect.X + picRect.Width / ,
picRect.Y + picRect.Height / );
// 绘图平面以图片的中心点旋转
graphics.TranslateTransform(Pcenter.X, Pcenter.Y);
graphics.RotateTransform(angle);
//恢复绘图平面在水平和垂直方向的平移
graphics.TranslateTransform(-Pcenter.X, -Pcenter.Y);
//绘制图片
graphics.DrawImage(image, picRect);
}

通过操作Graphics进行图像旋转,使用时需要注意图片是按原始大小进行居中旋转  PictureBox的SizeMode属性对这种方法无效。