OnDrawItem (C++)

From RAD Studio Code Examples
Jump to: navigation, search

Description

Here is a typical handler for an OnDrawItem event. In the example, a list box with the lbOwnerDrawFixed style draws a bitmap to the left of each string. Select the TListBox and set the ItemHeight property to 32. Select the ImageList and set the Layout Height and Width to 32. Double-click the ImageList to load the images. Be sure to load in the correct order: logo2, Sunflower, butterfly.

Code

#include <memory>       //For STL auto_ptr class

Graphics::TBitmap *bitmap0, *bitmap1, *bitmap2;

__fastcall TForm1::TForm1(TComponent* Owner)
  : TForm(Owner)
{
  static std::auto_ptr<Graphics::TBitmap> _bitmap0Cleaner(bitmap0 = new Graphics::TBitmap);
  static std::auto_ptr<Graphics::TBitmap> _bitmap1Cleaner(bitmap1 = new Graphics::TBitmap);
  static std::auto_ptr<Graphics::TBitmap> _bitmap2Cleaner(bitmap2 = new Graphics::TBitmap);

  ImageList1->GetBitmap(0, bitmap0);
  ListBox1->Items->AddObject("Flowers", bitmap0);
  ImageList1->GetBitmap(1, bitmap1);
  ListBox1->Items->AddObject("Animal", bitmap1);
  ImageList1->GetBitmap(2, bitmap2);
  ListBox1->Items->AddObject("Butterfly", bitmap2);
}

void __fastcall TForm1::ListBox1DrawItem(TWinControl *Control, int Index,
      TRect &Rect, TOwnerDrawState State)
{
  Graphics::TBitmap *pBitmap; // Temporary variable for the item�s bitmap
  int     Offset = 2;   // Default text offset width
  // Note that you draw on the listbox�s canvas, not on the form.
  TCanvas *pCanvas = (dynamic_cast<TListBox *>(Control))->Canvas;
  pCanvas->FillRect(Rect); // clear the rectangle
  pBitmap = dynamic_cast<Graphics::TBitmap *>((dynamic_cast<TListBox *>(Control))->Items->Objects[Index]);
  if (pBitmap)
  {
	pCanvas->BrushCopy(
	  Bounds(Rect.Left + Offset, Rect.Top, pBitmap->Width, pBitmap->Height),
	  pBitmap,
	  Bounds(0, 0, pBitmap->Width, pBitmap->Height), clRed); // render bitmap
    Offset += pBitmap->Width + 4;   // Add four pixels between bitmap and text.
  }
  // display the text
  pCanvas->TextOut(Rect.Left + Offset, Rect.Top, (dynamic_cast<TListBox *>(Control))->Items->Strings[Index]);
}

Uses