//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "OnDrawItem.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
	: TForm(Owner)
{
}
//---------------------------------------------------------------------------
// BeginExample: OnDrawItem
// Event: StdCtrls.TCustomListBox.OnDrawItem
// Property: StdCtrls.TCustomListBox.Canvas

// Warning: Need to call Destroy for all these classes (TBitmap, TStringList...).

// BeginCode
/*
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 on the ImageList to load the images.  Be
sure to load in the correct order, logo2, Sunflower,
butterfly.
*/
#include <memory>       //for STL auto_ptr class

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

void __fastcall TForm1::FormCreate(TObject *Sender)
{
  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 item’s bitmap
  int     Offset = 2;   // default text offset width
  // note that we 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]);
}
// EndCode
// EndExample: OnDrawItem
//---------------------------------------------------------------------------
