Set background image in ListBox

Posted in Components

You should use onDrawItem event of ListBox component, if you want to create ListBox with some background picture. Pay attention to the IntersectRect function.

procedure TForm1.ListBox1DrawItem(Control: TWinControl; Index: Integer;
  Rect: TRect; State: TOwnerDrawState);
var
  ImageRect1, NewRect, ImageRect2, ResRect: TRect;
begin
  ImageRect1 := Classes.Rect(
    0,
    0,
    Image1.Picture.Bitmap.Width,
    Image1.Picture.Bitmap.Height);

  ImageRect2 := ImageRect1;
  IntersectRect(ResRect, ImageRect2, Rect);

  NewRect.Left:=ImageRect1.Left;
  NewRect.Top:=ImageRect1.Top+ResRect.Top-ImageRect2.Top;
  NewRect.Right:=ImageRect1.Right;
  NewRect.Bottom:=ImageRect1.Bottom+
                    ResRect.Bottom-
                    ImageRect2.Bottom;

  ListBox1.Canvas.CopyRect(
    ResRect,
    Image1.Picture.Bitmap.Canvas,
    NewRect);

  ListBox1.Canvas.Brush.Style:=bsClear;
  ListBox1.Canvas.TextOut(
    Rect.Left+2,
    Rect.Top,
    ExtractFileName(ListBox1.Items[Index]));