Winform以任意角度旋轉PictureBox中的圖片的方法

方法1:spa

  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矩陣 對圖片進行旋轉。code

  缺點:有時圖片會越轉越模糊。orm

 

方法2:blog

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屬性對這種方法無效。圖片

相關文章
相關標籤/搜索