Delphi Cookbook
上QQ阅读APP看书,第一时间看更新

How to do it...

Let's look at the following steps:

  1. Create a brand new VCL application and drop a TListBox onto the form. Set the following properties:
    
      
        

Property           Value
Style           lbOwnerDrawFixed
Font.Size           14

  1. In the Items listbox property, add seven levels of discount. For example, you can use no discount, 10% discount, 20% discount, 30% discount, 40% discount, 50% discount, 60% discount, and 70% discount.
  2. Then, drop a TImageList component onto the form and set the following properties:
    
      
        

Property           Value
ColorDepth           cd32Bit
DrawingStyle           dsTransparent
Width           32
Height           32
  1. TImageList is our image repository and will be used to draw an image by index. Load seven PNG images (size 32 x 32) into TImageList. You can find some nice PNG icons in the respective recipe project folder (ICONS\PNG\32).
  2. Create an OnDrawItem event handler for TListBox and write the following code:
procedure TMainForm.ListBox1DrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
var
LBox: TListBox;
R: TRect;
S: string;
TextTopPos, TextLeftPos, TextHeight: Integer;
const
IMAGE_TEXT_SPACE = 5;
begin
LBox := Control as TListBox;
R := Rect;
LBox.Canvas.FillRect(R);
ImageList1.Draw(LBox.Canvas, R.Left, R.Top, Index);
S := LBox.Items[Index];
TextHeight := LBox.Canvas.TextHeight(S);
TextLeftPos := R.Left + ImageList1.Width + IMAGE_TEXT_SPACE;
TextTopPos := R.Top + R.Height div 2 - TextHeight div 2;
LBox.Canvas.TextOut(TextLeftPos, TextTopPos, S);
end;
  1. Run the application by hitting F9 (or by going to Run | Run) and you will see the following:
Figure 1.7: Our listbox with some custom icons read from TImageList