通過路徑的輔助類 TGPGraphicsPathIterator , 可以獲得更多路徑數據和控制能力.
本例效果圖:
代碼文件:unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormPaint(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses GDIPOBJ, GDIPAPI;
var
path: TGPGraphicsPath;
procedure TForm1.FormCreate(Sender: TObject);
var
pt1, pt2: TPoint;
begin
Button1.Caption := '查看路徑基本數據';
Button2.Caption := '重繪路徑中的子路徑';
pt1 := Point(30, 20);
pt2 := Point(150, 120);
{建立路徑, 並添加四個子圖形}
path := TGPGraphicsPath.Create;
path.StartFigure;
path.AddRectangle(MakeRect(Rect(pt1, pt2)));
path.CloseFigure;
path.StartFigure;
path.AddEllipse(MakeRect(Rect(pt1, pt2)));
path.CloseFigure;
path.StartFigure;
path.AddLine(pt1.X, pt1.Y, pt2.X, pt2.Y);
path.CloseFigure;
path.StartFigure;
path.AddLine(pt1.X, pt2.Y, pt2.X, pt1.Y);
path.CloseFigure;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
path.Free;
end;
procedure TForm1.FormPaint(Sender: TObject);
var
g: TGPGraphics;
p: TGPPen;
begin
g := TGPGraphics.Create(Canvas.Handle);
p := TGPPen.Create(aclSilver, 2);
g.DrawPath(p, path);
p.Free;
g.Free;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
PathIterator: TGPGraphicsPathIterator;
str: string;
begin
PathIterator := TGPGraphicsPathIterator.Create(path);
str := str + Format('路徑中的總點數: %d', [PathIterator.GetCount]);
str := str + Format(sLineBreak + '路徑中的子路徑數: %d', [PathIterator.GetSubpathCount]);
str := str + Format(sLineBreak + '路徑中是否包含曲線: %s', [BoolToStr (PathIterator.HasCurve, True)]);
ShowMessage(str);
PathIterator.Free;
end;
procedure TForm1.Button2Click(Sender: TObject);
const
ColorArr: array[0..3] of TGPColor = (aclRed, aclGreen, aclBlue, aclYellow);
var
PathIterator: TGPGraphicsPathIterator;
PathSection: TGPGraphicsPath;
bool: LongBool;
g: TGPGraphics;
p: TGPPen;
i: Integer;
begin
g := TGPGraphics.Create(Canvas.Handle);
p := TGPPen.Create(aclRed, 2);
PathIterator := TGPGraphicsPathIterator.Create(path);
PathIterator.Rewind; {到路徑起始點}
for i := 0 to PathIterator.GetSubpathCount - 1 do
begin
PathSection := TGPGraphicsPath.Create;
PathIterator.NextSubpath(PathSection, bool);
p.SetColor(ColorArr[i]);
g.DrawPath(p, PathSection);
PathSection.Free;
end;
PathIterator.Free;
p.Free;
g.Free;
end;
end.