RAD Studio VCL Reference
ContentsIndex
PreviousUpNext
TCustomForm.Canvas Property

Provides access to the drawing area of the form.

Pascal
property Canvas: TCanvas;
C++
__property TCanvas Canvas;

Use TCanvas to draw on the client area of the form. Canvas is often used in the OnPaint event handler.  

C++ Examples: 

 

/*
The following code loads a bitmap from a file and assigns it
to the Brush of the Canvas of Form1:
*/

#include <memory>       //for STL auto_ptr class

void __fastcall TForm1::Button1Click(TObject *Sender)
{
  std::auto_ptr<Graphics::TBitmap> BrushBmp(new Graphics::TBitmap);
  BrushBmp->LoadFromFile("../bm1.BMP");
  Form1->Canvas->Brush->Bitmap = BrushBmp.get();
  Form1->Canvas->FillRect(Rect(0,0,100,100));
  Form1->Canvas->Brush->Bitmap = NULL;
}
/*
The following code uses ClientRect to find and draw a line
from the top left to the bottom right of the current
control.  Select a TControl in the ListBox list.  This
example assumes that the current object is a descendent of
TControl and has a public Canvas property.
*/
{
  TPoint APoint = Point(X, Y);
  int Index = ListBox1->ItemAtPos(APoint, True);
  TForm1 *myForm;
  TClass ClassRef = ListBox1->Items->Objects[Index]->ClassType();
  if (String(ClassRef->ClassName()) == "TForm1")
  {
    myForm = dynamic_cast<TForm1 *>(ListBox1->Items->Objects[Index]);
    // make sure we are using the TControls canvas and not the from's!
    myForm->Canvas->MoveTo(myForm->ClientRect.Left, myForm->ClientRect.Top);
    myForm->Canvas->LineTo(myForm->ClientRect.Right, myForm->ClientRect.Bottom);
    myForm = NULL;
  }
}

 

Delphi Examples: 

{
The following code uses ClientRect to find and draw a line
from the top left to the bottom right of the current
control.  Select a TControl in the ListBox list.  This
example assumes that the current object is a descendent of
TControl and has a public Canvas property.
}
  if (ListBox1.Items.Objects[Index] is TForm1) then
  begin
    myForm:= (ListBox1.Items.Objects[Index] as TForm1);
    with myForm.ClientRect do
    begin // make sure we are using the TControl's canvas and not the form's!
      myForm.Canvas.MoveTo(Left, Top);
      myForm.Canvas.LineTo(Right, Bottom);
    end;
  myForm:= nil;
  end;
{
The following code loads a bitmap from a file and assigns it
to the Brush of the Canvas of Form1:
} 
var
  Bitmap: TBitmap;

procedure TForm1.Button1Click(Sender: TObject);
begin
  Bitmap := TBitmap.Create;
  try
    Bitmap.LoadFromFile('bm1.BMP');
    Form1.Canvas.Brush.Bitmap := Bitmap;
    Form1.Canvas.FillRect(Rect(0,0,100,100));
  finally
    Form1.Canvas.Brush.Bitmap := nil;
    Bitmap.Free;
  end;
end; 

 

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