Graphics.RotateTransform(angle) 設定繪圖座標系旋轉角度(度數),後續繪製操作皆受影響。搭配 TextureBrush 以影像填充矩形,即可達到影像旋轉效果。
private void btnRotate_Click(object sender, EventArgs e)
{
float angle = 0f;
using (Graphics g = panel1.CreateGraphics())
{
while (angle < 360)
{
// 以影像建立材質筆刷
using (var brush = new TextureBrush(_bitmap))
{
// 旋轉筆刷座標系
brush.RotateTransform(angle);
// 填充整個面板(或指定區域)
g.FillRectangle(brush, 0, 0, panel1.Width, panel1.Height);
}
angle += 0.5f;
Thread.Sleep(50); // 簡易延遲,實務請用 Timer/Task
}
}
}
RotateTransform 預設以原點 (0,0) 為旋轉中心。若要以影像中心旋轉,需結合 TranslateTransform:
private void DrawRotatedImage(Graphics g, Image img, float angle, PointF center)
{
// 1. 將原點移至旋轉中心
g.TranslateTransform(center.X, center.Y);
// 2. 旋轉
g.RotateTransform(angle);
// 3. 將原點移回,使影像中心對齊 center
g.TranslateTransform(-img.Width / 2f, -img.Height / 2f);
// 4. 繪製
g.DrawImage(img, 0, 0, img.Width, img.Height);
// 5. 重置變換(重要!避免影響後續繪圖)
g.ResetTransform();
}
public partial class RotateForm : Form
{
private readonly Bitmap _bitmap;
private float _angle = 0f;
private readonly System.Windows.Forms.Timer _timer;
public RotateForm()
{
InitializeComponent();
_bitmap = new Bitmap("logo.png");
this.DoubleBuffered = true; // 開啟雙緩衝
_timer = new System.Windows.Forms.Timer { Interval = 30 };
_timer.Tick += (s, e) =>
{
_angle = (_angle + 2f) % 360f;
this.Invalidate(); // 觸發 OnPaint
};
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
DrawRotatedImage(e.Graphics, _bitmap, _angle,
new PointF(this.ClientSize.Width / 2f, this.ClientSize.Height / 2f));
}
private void btnStart_Click(object sender, EventArgs e) => _timer.Start();
private void btnStop_Click(object sender, EventArgs e) => _timer.Stop();
}
| 問題 | 說明 | 對策 |
|---|---|---|
| 記憶體快速增長 | 迴圈中重複 new TextureBrush 未 Dispose | using 區塊或手動 Dispose() |
| CPU 佔用高 | 無延遲的 while 迴圈 | 使用 Timer 或 Task.Delay 控制幀率 |
| 閃爍 | 直接在 CreateGraphics 繪圖 | 改用 OnPaint + DoubleBuffered = true |
| 畫質模糊 | 預設插值模式 | g.InterpolationMode = InterpolationMode.HighQualityBicubic |
RenderTransform + RotateTransform,GPU 加速、保真度高canvas.RotateDegrees(angle),效能優於 GDI+GDI+ RotateTransform 適合簡單旋轉需求;若需高幀率、抗鋸齒、3D 效果或跨平台,建議升級至 WPF/SkiaSharp/Unity 等現代繪圖架構。