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:
*/
void __fastcall TForm1::Button1Click(TObject *Sender)
{
  Graphics::TBitmap *BrushBmp = new Graphics::TBitmap;
  try
  {
    BrushBmp->LoadFromFile("../bm1.BMP");
    Form1->Canvas->Brush->Bitmap = BrushBmp;
    Form1->Canvas->FillRect(Rect(0,0,100,100));
  }
  __finally
  {
    Form1->Canvas->Brush->Bitmap = NULL;
    delete BrushBmp;
  }
}
/*
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 = (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) 2008 CodeGear(TM). All Rights Reserved.
What do you think about this topic? Send feedback!