TDIB.Mirror 提供水平、垂直、雙向鏡像翻轉,本文提供四種翻轉模式的完整對比範例。

unit Unit1;
interface
uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DIB, StdCtrls;
type
TForm1 = class(TForm)
DXPaintBox1: TDXPaintBox;
Button1: TButton; // 載入圖片
Button2: TButton; // 水平鏡像
Button3: TButton; // 垂直鏡像
Button4: TButton; // 雙向鏡像
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
end;
var Form1: TForm1;
implementation {$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
const ImgPath1 = 'C:\Temp\DX.jpg';
begin
DXPaintBox1.DIB.LoadFromFile(ImgPath1);
DXPaintBox1.Width := DXPaintBox1.DIB.Width;
DXPaintBox1.Height := DXPaintBox1.DIB.Height;
DXPaintBox1.Repaint;
end;
procedure TForm1.Button2Click(Sender: TObject); // 水平
begin
// Mirror(Horizontal, Vertical: Boolean)
DXPaintBox1.DIB.Mirror(True, False);
DXPaintBox1.Repaint;
end;
procedure TForm1.Button3Click(Sender: TObject); // 垂直
begin
DXPaintBox1.DIB.Mirror(False, True);
DXPaintBox1.Repaint;
end;
procedure TForm1.Button4Click(Sender: TObject); // 雙向
begin
DXPaintBox1.DIB.Mirror(True, True);
DXPaintBox1.Repaint;
end;
end.
| Horizontal | Vertical | 效果 | 座標變換 |
|---|---|---|---|
| True | False | 左右鏡像 | X' = Width - 1 - X |
| False | True | 上下翻轉 | Y' = Height - 1 - Y |
| True | True | 180° 旋轉 | X', Y' 皆翻轉 |
| False | False | 無變化 | 恆等 |
procedure MirrorAxis(DIB: TDIB; CenterX, CenterY: Integer; AngleDeg: Real);
var x, y, nx, ny: Integer; c: TRGBQuad; cosA, sinA: Double;
begin
cosA := Cos(AngleDeg * Pi / 180); sinA := Sin(AngleDeg * Pi / 180);
// 需建立副本避免覆蓋未讀像素
var Backup := TDIB.Create; Backup.Assign(DIB);
for y := 0 to DIB.Height - 1 do
for x := 0 to DIB.Width - 1 do begin
// 平移到原點 -> 旋轉 2*Angle -> 平移回
nx := Round((x - CenterX) * cosA * 2 - (y - CenterY) * sinA * 2 + CenterX);
ny := Round((x - CenterX) * sinA * 2 + (y - CenterY) * cosA * 2 + CenterY);
if (nx >= 0) and (nx < DIB.Width) and (ny >= 0) and (ny < DIB.Height) then
DIB.Pixels[x, y] := Backup.Pixels[nx, ny];
end;
Backup.Free;
end;