OnDrawItem (Delphi)
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
procedure TForm1.FormCreate(Sender: TObject);
begin
MyList := TStringList.Create;
bitmap0 := TBitmap.Create; // These objects are created without an owner, so they must be explicitly deleted.
bitmap1 := TBitmap.Create; // They are added to an ImageList, which also will not delete them when it is destroyed.
bitmap2 := TBitmap.Create;
// MyList.Add('Animal');
// MyList.Add('Flowers');
// MyList.Add('Butterfly');
// ListBox1.Items.AddStrings(MyList);
ImageList1.GetBitmap(0, bitmap0);
ListBox1.Items.AddObject('Flowers', bitmap0); // Adding bitmap0 to an ImageList does not copy bitmap0.
ImageList1.GetBitmap(1, bitmap1); // So, you can't destroy bitmap0 as long as the image list needs it.
ListBox1.Items.AddObject('Animal', bitmap1);
ImageList1.GetBitmap(2, bitmap2);
ListBox1.Items.AddObject('Butterfly', bitmap2);
end;
procedure TForm1.ListBox1DrawItem(Control: TWinControl; Index: Integer; Rect:TRect; State: TOwnerDrawState);
var
Bitmap: TBitmap; { Temporary variable for the item�s bitmap }
Offset: Integer; { Text offset width }
begin
Bitmap := TBitmap.Create;
with (Control as TListBox).Canvas do { Draw on control canvas, not on the form. }
begin
FillRect(Rect); { Clear the rectangle. }
Offset := 2; { Provide default offset. }
Bitmap := TBitmap((Control as TListBox).Items.Objects[Index]); { Get the bitmap. }
if Bitmap <> nil then
begin
BrushCopy(
Bounds(Rect.Left + Offset, Rect.Top, Bitmap.Width, Bitmap.Height),
Bitmap,
Bounds(0, 0, Bitmap.Width, Bitmap.Height),
clRed); {render bitmap}
Offset := Bitmap.width + 6; { Add four pixels between bitmap and text. }
end;
TextOut(Rect.Left + Offset, Rect.Top, (Control as TListBox).Items[Index]) { Display the text. }
end;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
MyList.Free;
bitmap0.Free;
bitmap1.Free;
bitmap2.Free;
end;
Uses
- Vcl.StdCtrls.TCustomListBox.OnDrawItem ( fr | de | ja )
- Vcl.StdCtrls.TCustomListBox.Canvas ( fr | de | ja )