首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> Delphi

再學GDI+[59]: 路徑迭代器 TGPGraphicsPathIterator 進階應用 - 子路徑枚舉與屬性查詢

     編輯:Delphi

前言

TGPGraphicsPathIterator 是路徑的輔助類別,提供強大的子路徑枚舉、點數統計、曲線偵測等進階功能。本文示範如何建立包含多個子圖形的複合路徑,並透過迭代器逐一提取、著色繪製每個子路徑。

迭代器核心功能

方法功能回傳值
GetCount路徑總點數Integer
GetSubpathCount子路徑個數Integer
HasCurve是否包含貝塞爾曲線Boolean
NextSubpath(path, closed)提取下一個子路徑Integer (點數)
Rewind重置迭代器到起始-

四子路徑複合範例

建立包含矩形、橢圓、對角線、反對角線四個獨立子路徑的複合路徑。

procedure TForm1.FormCreate(Sender: TObject);
var
  pt1, pt2: TPoint;
begin
  pt1 := Point(30, 20); pt2 := Point(150, 120);
  path := TGPGraphicsPath.Create;
  
  path.StartFigure;  {子路徑 1: 矩形}
  path.AddRectangle(MakeRect(Rect(pt1, pt2)));
  path.CloseFigure;
  
  path.StartFigure;  {子路徑 2: 橢圓}
  path.AddEllipse(MakeRect(Rect(pt1, pt2)));
  path.CloseFigure;
  
  path.StartFigure;  {子路徑 3: 對角線}
  path.AddLine(pt1.X, pt1.Y, pt2.X, pt2.Y);
  path.CloseFigure;
  
  path.StartFigure;  {子路徑 4: 反對角線}
  path.AddLine(pt1.X, pt2.Y, pt2.X, pt1.Y);
  path.CloseFigure;
end;

按鈕功能實作

按鈕 1:查看路徑基本數據

procedure TForm1.Button1Click(Sender: TObject);
var
  PathIterator: TGPGraphicsPathIterator;
  str: string;
begin
  PathIterator := TGPGraphicsPathIterator.Create(path);
  str := Format('路徑總點數: %d', [PathIterator.GetCount]);
  str := str + Format(#13#10 + '子路徑數: %d', [PathIterator.GetSubpathCount]);
  str := str + Format(#13#10 + '包含曲線: %s', [BoolToStr(PathIterator.HasCurve, True)]);
  ShowMessage(str);
  PathIterator.Free;
end;

按鈕 2:重繪各子路徑(不同顏色)

procedure TForm1.Button2Click(Sender: TObject);
const
  ColorArr: array[0..3] of TGPColor = (aclRed, aclGreen, aclBlue, aclYellow);
var
  PathIterator: TGPGraphicsPathIterator;
  PathSection: TGPGraphicsPath;
  closed: 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, closed);
    p.SetColor(ColorArr[i]);
    g.DrawPath(p, PathSection);
    PathSection.Free;
  end;
  
  PathIterator.Free; p.Free; g.Free;
end;

執行效果預覽

路徑迭代器子路徑枚舉

進階應用場景

  • 路徑編輯器:選中、移動、刪除特定子路徑
  • SVG 匯入/匯出:解析複合路徑結構
  • 碰撞偵測優化:針對特定子路徑進行精確測試
  • 動畫路徑分解:依序播放各子路徑動畫

表單定義檔

object Form1: TForm1
  Left = 0
  Top = 0
  Caption = 'Form1'
  ClientHeight = 198
  ClientWidth = 181
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = False
  Position = poDesktopCenter
  OnCreate = FormCreate
  OnDestroy = FormDestroy
  OnPaint = FormPaint
  PixelsPerInch = 96
  TextHeight = 13
  object Button1: TButton ... {兩個按鈕定義}
end
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved