Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi image canvas... paint an area (triangle, rectangle, polygons)

Tags:

delphi

I have a variable number of points on a canvas. Sometime its four other times 3 points, or 6. Is there a function that can paint the area inside?

Thank you for your help.

like image 738
Panos Kal. Avatar asked Apr 03 '12 18:04

Panos Kal.


3 Answers

As a complement to both TLama's and Andreas answer, here's another alternative :

procedure TForm1.Button1Click(Sender: TObject);
begin
  Canvas.Pen.Color := clRed;
  Canvas.Brush.Color := clYellow;
  Self.Canvas.Polygon( [Point(5,5), Point(55,5), Point(30,30)]);
end;

Utilizing open array construct and Point record.

like image 69
LU RD Avatar answered Sep 17 '22 18:09

LU RD


Use the TCanvas.Polygon function. Declare an array of TPoint, set its length to the count of your points, specify each point's coordinates (optionally modify canvas pen and/or brush) and pass this array to the TCanvas.Polygon function. Like in this boring example:

procedure TForm1.Button1Click(Sender: TObject);
var
  Points: array of TPoint;
begin
  SetLength(Points, 3);
  Points[0] := Point(5, 5);
  Points[1] := Point(55, 5);
  Points[2] := Point(30, 30);
  Canvas.Pen.Width := 2;
  Canvas.Pen.Color := clRed;
  Canvas.Brush.Color := clYellow;
  Canvas.Polygon(Points);
end;

Here's how it looks like:

enter image description here

like image 17
TLama Avatar answered Nov 08 '22 01:11

TLama


As a complement to TLama's excellent answer, this is a case where you can obtain pretty convenient syntax using the open array construct. Consider the helper function

procedure DrawPolygon(Canvas: TCanvas; const Points: array of integer);
var
  arr: array of TPoint;
  i: Integer;
begin
  SetLength(arr, Length(Points) div 2);
  for i := 0 to High(arr) do
    arr[i] := Point(Points[2*i], Points[2*i+1]);
  Canvas.Polygon(arr);
end;

defined and implemented once and for all. Now you can do simply

Canvas.Pen.Width := 2;
Canvas.Pen.Color := clRed;
Canvas.Brush.Color := clYellow;
DrawPolygon(Canvas, [5, 5, 55, 5, 30, 30]);

to draw the same figure as in TLama's example.

like image 16
Andreas Rejbrand Avatar answered Nov 08 '22 01:11

Andreas Rejbrand