Creating Drawing Spaces

From RAD Studio
Jump to: navigation, search

Go Up to Using the Properties of the Canvas Object


The Vcl.Graphics.TCanvas class encapsulates a Windows device context. This class handles all drawing for forms, visual containers (such as panels) and the printer object (see Printing in VCL Applications). Using the canvas object, you need not worry about allocating pens, brushes, palettes, and so on - all the allocation and deallocation are handled for you.

TCanvas includes a large number of primitive graphics routines to draw lines, shapes, polygons, fonts, etc. onto any control that contains a canvas. For example, here is a button event handler that draws a line from the upper left corner to the middle of the form and outputs some raw text onto the form:

Delphi:

 procedure TForm1.Button1Click(Sender: TObject);
   begin
     Canvas.Pen.Color := clBlue;
     Canvas.MoveTo( 10, 10 );
     Canvas.LineTo( 100, 100 );
     Canvas.Brush.Color := clBtnFace;
     Canvas.Font.Name := 'Arial';
     Canvas.TextOut( Canvas.PenPos.x, Canvas.PenPos.y,'This is the end of the line' );
   end;

C++:

void __fastcall TForm1::Button1Click(TObject *Sender) {
    Canvas->Pen->Color = clBlue;
    Canvas->MoveTo(10, 10);
    Canvas->LineTo(100, 100);
    Canvas->Brush->Color = clBtnFace;
    Canvas->Font->Name = "Arial";
    Canvas->TextOut(Canvas->PenPos.x, Canvas->PenPos.y,
        "This is the end of the line");
}

The TCanvas object defined in the Graphics unit also protects you against common Windows graphics errors, such as restoring device contexts, pens, brushes, and so on to the value they had before the drawing operation. TCanvas is used everywhere in the VCL that drawing is required or possible, and makes drawing graphics both fail-safe and easy.

See Also