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

GDI+ 多邊形繪製:DrawPolygon 點陣列構建任意多邊形

     編輯:Delphi

DrawPolygon 根據點陣列依序連線,並自動閉合首尾點,繪製任意多邊形。點陣列可為靜態或動態陣列,配合滑鼠點擊動態增點,即構成互動式多邊形編輯器。

參數說明

g.DrawPolygon(p, PGPPoint(PtArr), Length(PtArr));
  • PtArr:TGPPoint 陣列,至少 3 點
  • 自動連接最後一點回第一點形成閉合

程式碼實作

滑鼠左鍵點擊新增頂點,按鈕清空/重繪:

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    procedure FormMouseUp(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure FormPaint(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}
uses GDIPOBJ, GDIPAPI;

var
  PtArr: array of TGPPoint;
  i: Integer = 0;

procedure TForm1.FormMouseUp(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  Canvas.Ellipse(X - 2, Y - 2, X + 2, Y + 2);
  Inc(i);
  SetLength(PtArr, i);
  PtArr[i - 1].X := X;
  PtArr[i - 1].Y := Y;
  Text := IntToStr(i);
end;

procedure TForm1.FormPaint(Sender: TObject);
var
  g: TGPGraphics;
  p: TGPPen;
begin
  g := TGPGraphics.Create(Canvas.Handle);
  p := TGPPen.Create(aclRed, 2);
  g.Clear(aclWhite);
  g.DrawPolygon(p, PGPPoint(PtArr), Length(PtArr));
  g.Free;
  p.Free;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  i := 0;
  SetLength(PtArr, i);
  Repaint;
  Text := IntToStr(i);
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  Repaint;
end;

end.

表單設計 (DFM)

object Form1: TForm1
  Left = 0
  Top = 0
  Caption = 'Form1'
  ClientHeight = 188
  ClientWidth = 264
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = False
  Position = poDesktopCenter
  OnMouseUp = FormMouseUp
  OnPaint = FormPaint
  PixelsPerInch = 96
  TextHeight = 13
  object Button1: TButton
    Left = 98
    Top = 155
    Width = 75
    Height = 25
    Caption = #25830#38500
    TabOrder = 0
    OnClick = Button1Click
  end
  object Button2: TButton
    Left = 179
    Top = 155
    Width = 75
    Height = 25
    Caption = #32472#21046
    TabOrder = 1
    OnClick = Button2Click
  end

執行效果

DrawPolygon 多邊形示範

進階應用提示

  • 配合 FillPolygon 實現多邊形填充
  • 使用 TGPGraphicsPath 可構建複雜路徑 (含曲線段)
  • 頂點順序決定繪製方向 (順/逆時針),影響填充規則 (Alternate/Winding)
  • 可擴展為多邊形編輯器:拖曳頂點、插入/刪除頂點、吸附對齊
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved