RAD Studio VCL Reference
ContentsIndex
PreviousUpNext
TCanvas.Rectangle Method (Integer, Integer, Integer, Integer)

Draws a rectangle on the canvas.

Pascal
procedure Rectangle(X1: Integer; Y1: Integer; X2: Integer; Y2: Integer); overload;
procedure Rectangle(const Rect: TRect); overload;
C++
__fastcall Rectangle(int X1, int Y1, int X2, int Y2);
__fastcall Rectangle(const TRect Rect);

Use Rectangle to draw a rectangle using Pen and fill it with Brush. Specify the rectangle's coordinates in one of two ways: 

Giving four coordinates that define the upper left corner at the point (X1, Y1) and the lower right corner at the point (X2, Y2). 

Using a TRect type. 

To fill a rectangular region without drawing the boundary in the current pen, use FillRect. To outline a rectangular region without filling it, use FrameRect or Polygon. To draw a rectangle with rounded corners, use RoundRect.  

C++ Examples: 

 

/*
This example draws many rectangles of various sizes and
colors on a form maximized to fill the entire screen. To run
the code, drop a TTimer component on the form and use the
object inspector to create the OnTimer and OnActivate event
handlers.
*/
int x, y;

void __fastcall TForm1::FormActivate(TObject *Sender)
{
  WindowState = wsMaximized;
  Timer1->Interval = 50;
  randomize();
}

void __fastcall TForm1::Timer1Timer(TObject *Sender)
{
  x = random(Screen->Width - 10);
  y = random(Screen->Height - 10);
  Canvas->Pen->Color = (Graphics::TColor) random(65535);
  switch (random(5))
  {
    case 0: Canvas->Pen->Style = psSolid; break;
    case 1: Canvas->Pen->Style = psDash; break;
    case 2: Canvas->Pen->Style = psDot; break;
    case 3: Canvas->Pen->Style = psDashDot; break;
    case 4: Canvas->Pen->Style = psDashDotDot; break;
  }
  Canvas->Rectangle(x, y, x + random(400), y + random(400));
}

 

Delphi Examples: 

{
This example draws many rectangles of various sizes and
colors on a form maximized to fill the entire screen. To run
the code, drop a TTimer component on the form and use the
object inspector to create the OnTimer and OnActivate event
handlers.
}
var
  X, Y: Integer;
procedure TForm1.FormActivate(Sender: TObject);
begin
  WindowState := wsMaximized;
  Timer1.Interval := 50;
  Randomize;
end;

procedure TForm1.Timer1Timer(Sender: TObject);
begin
  X := Random(Screen.Width - 10);
  Y := Random(Screen.Height - 10);
  Canvas.Pen.Color := Random(65535);
  case Random(5) of
    0: Canvas.Pen.Style := psSolid;
    1: Canvas.Pen.Style := psDash;
    2: Canvas.Pen.Style := psDot;
    3: Canvas.Pen.Style := psDashDot;
    4: Canvas.Pen.Style := psDashDotDot;
  end;
  Canvas.Rectangle(X, Y, X + Random(400), Y + Random(400));
end;

 

Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!