方法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(0, 0, pb.Width, pb.Height);
            PointF center = new PointF(rect.Width / 2, rect.Height / 2);
            float offsetX = 0;
            float offsetY = 0;
            offsetX = center.X - image.Width / 2;
            offsetY = center.Y - image.Height / 2;
            //构造图片显示区域:让图片的中心点与窗口的中心点一致
            RectangleF picRect = new RectangleF(offsetX, offsetY, image.Width, image.Height);
            PointF Pcenter = new PointF(picRect.X + picRect.Width / 2,
                picRect.Y + picRect.Height / 2);
            // 绘图平面以图片的中心点旋转
            graphics.TranslateTransform(Pcenter.X, Pcenter.Y);
            graphics.RotateTransform(angle);
            //恢复绘图平面在水平和垂直方向的平移
            graphics.TranslateTransform(-Pcenter.X, -Pcenter.Y);
            //绘制图片
            graphics.DrawImage(image, picRect);
}

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

posted on 2016-03-30 13:02  Mr.Owl  阅读(8034)  评论(8编辑  收藏  举报