c#圖片在PictureBox內任意角度旋轉問題(360度)
阿新 • • 發佈:2019-02-16
(1)
public static Bitmap RotateImage(Image image, float angle) { if (image == null) throw new ArgumentNullException("image"); float dx = image.Width / 2.0f; float dy = image.Height / 2.0f; Bitmap rotatedBmp = new Bitmap(image.Width, image.Height); rotatedBmp.SetResolution(image.HorizontalResolution, image.VerticalResolution); Graphics g = Graphics.FromImage(rotatedBmp); g.TranslateTransform(dx, dy); g.RotateTransform(angle); g.TranslateTransform(-dx, -dy); g.DrawImage(image, new PointF(0, 0)); return rotatedBmp; } void tm_Elapsed(object sender, EventArgs e) { if (isStart) { angle += 5; if (angle >= 359) angle = 0; RotateImage(pic1, Properties.Resources._1, angle); } } private void RotateImage(PictureBox pb, Image img, float angle) { if (img == null || pb.Image == null) return; Image oldImage = pb.Image; pb.Image = Utilities.RotateImage(img, angle); if (oldImage != null) { oldImage.Dispose(); } }
(2)
//任意角度旋轉 private void RotateTransformButton_Click(object sender, EventArgs e) { try { Bitmap a = new Bitmap(pictureBox1.Image);//得到圖片框中的圖片 pictureBox1.Image = Rotate(a, Convert.ToInt32(textBox1.Text)); pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize; pictureBox1.Location = panel1.Location; pictureBox1.Refresh();//最後重新整理圖片框 } catch { } } #region 圖片旋轉函式 /// <summary> /// 以逆時針為方向對影象進行旋轉 /// </summary> /// <param name="b">點陣圖流</param> /// <param name="angle">旋轉角度[0,360](前臺給的)</param> /// <returns></returns> public Bitmap Rotate(Bitmap b, int angle) { angle = angle % 360; //弧度轉換 double radian = angle * Math.PI / 180.0; double cos = Math.Cos(radian); double sin = Math.Sin(radian); //原圖的寬和高 int w = b.Width; int h = b.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 dsImage = new Bitmap(W, H); Graphics g = Graphics.FromImage(dsImage); g.InterpolationMode = InterpolationMode.Bilinear; 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.TranslateTransform(center.X, center.Y); g.RotateTransform(360 - angle); //恢復影象在水平和垂直方向的平移 g.TranslateTransform(-center.X, -center.Y); g.DrawImage(b, rect); //重至繪圖的所有變換 g.ResetTransform(); g.Save(); g.Dispose(); return dsImage; } #endregion 圖片旋轉函式