在Image上绘制多边形

时间:2013-03-20 21:19:52

标签: delphi delphi-xe2

我一直在搜索这段时间,但无法得到答案。

我想在图像上绘制多边形,但我想通过创建点来做到这一点; 使用MouseCursor创建此特定点,并使用按钮沿这些点绘制一条线;

我发现了这个:

var
  Poly: array of TPoint;
begin  
   // Allocate dynamic array of TPoint
   SetLength(Poly, 6);

  // Set array elements
  Poly[0] := Point(10, 10);
  Poly[1] := Point(30, 5);
  Poly[2] := Point(100, 20);
  Poly[3] := Point(120, 100);
  Poly[4] := Point(50, 120);
  Poly[5] := Point(10, 60);

  // Pass to drawing routine
  Canvas.Polygon(Poly);

  // Redim if needed
  SetLength(Poly, 7);
  Poly[6] := Point(1, 5);

  // Pass to drawing routine
  Canvas.Polygon(Poly);
end;

这就是我想要的,但区别在于Point[1]Point[2]等由用户MouseEvent提供。

2 个答案:

答案 0 :(得分:4)

您可以在图像上叠加一个Paintbox并使用像这样的代码

unit Unit3;

interface

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

type
  TPointArray=array of TPoint;
  TForm3 = class(TForm)
    Image1: TImage;
    PaintBox1: TPaintBox;
    Button1: TButton;
    procedure PaintBox1MouseDown(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure PaintBox1Paint(Sender: TObject);
    procedure Button1Click(Sender: TObject);
  private
    { Private-Deklarationen }
    FPointArray:TPointArray;
  public
    { Public-Deklarationen }
  end;
var
  Form3: TForm3;
implementation
{$R *.dfm}

procedure TForm3.Button1Click(Sender: TObject);
begin
   PaintBox1.Visible := false;
   Image1.Canvas.Polygon(FPointArray);
end;

procedure TForm3.PaintBox1MouseDown(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
   SetLength(FPointArray,Length(FPointArray)+1);
   FPointArray[High(FPointArray)].X := X;
   FPointArray[High(FPointArray)].Y := Y;
   Paintbox1.Invalidate;
end;

procedure TForm3.PaintBox1Paint(Sender: TObject);
var
 i:Integer;
begin
  PaintBox1.Canvas.Brush.Style := bsClear; //as suggested by TLama
  PaintBox1.Canvas.Polygon(FPointArray);
  for I := 0 to High(FPointArray) do
      begin
        PaintBox1.Canvas.TextOut(FPointArray[i].X-5,FPointArray[i].y-5,IntToStr(i));
      end;
end;

end.

答案 1 :(得分:2)

制作表单管理的点数组。在表单类中声明一个动态数组字段:

private
  FPoly: array of TPoint;

OnClick事件中,延长数组并为其添加新坐标:

procedure TFruitForm.ImageClick(Sender: TObject);
var
  p: TPoint;
begin
  p := ...;
  SetLength(FPoly, Length(FPoly) + 1);
  FPoly[High(FPoly)] := p;
end;

要指定p,请参阅How do I get the coordinates of the mouse when a control is clicked?

您可能还考虑使用通用列表而不是数组:TList<TPoint>