RAD Studio
ContentsIndex
PreviousUpNext
Displaying a Bitmap Image in a VCL Forms Application

This procedure loads a bitmap image from a file and displays it to a VCL form.

  1. Create a VCL form with a button control.
  2. Provide a bitmap image.
  3. Code the button's onClick event handler to load and display a bitmap image.
  4. Build and run the application.

To create a VCL form and button

  1. Choose FileNewOtherDelphi Projects or C++Builder Projects and double-click the VCL Forms Application icon. The VCL Forms Designer is displayed.
  2. From the Standard page of the Tool Palette, place a TButton component on the form.

To provide a bitmap image

  1. Create a directory in which to store your project files.
  2. Locate a bitmap image on your local drive, and copy it to your project directory.
  3. Save all files in your project to your project directory.

To write the OnClick event handler

  1. In the Object Inspector, double-click the Button1 OnClick event on the Events tab. The Code Editor displays with the cursor in the TForm1.Button1Click (Delphi) or TForm1::Button1Click (C++) event handler block.
  2. Enter the following event handling code, replacing MyFile.bmp with path to the bitmap image in your project directory:

Bitmap := TBitmap.Create;
try
  Bitmap.LoadFromFile('MyFile.bmp');
  Form1.Canvas.Brush.Bitmap := Bitmap;
  Form1.Canvas.FillRect(Rect(0,0,100,100));
finally
  Form1.Canvas.Brush.Bitmap := nil;
  Bitmap.Free;
end;

 

Graphics::TBitmap *Bitmap = new Graphics::TBitmap();
try {
  Bitmap->LoadFromFile( "..\\MyFile.bmp" );
  Form1->Canvas->Brush->Bitmap = Bitmap;
  Form1->Canvas->FillRect( Rect(0,0,100,100) );
} __finally {
  Form1->Canvas->Brush->Bitmap = NULL;
  Bitmap->Free();
}

Note: For C++ projects, the code assumes the target output directory is located in the project directory.
Tip: You can change the size of the rectangle to be displayed by adjusting the Rect parameter values.
  1. For Delphi, add the following variable declaration in the var block:

Bitmap : TBitmap;
To run the program

  1. Select RunRun.
  2. Click the button to display the image bitmap in a 100 x 100-pixel rectangle in the upper left corner of the form.

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