ListBox填充背景,图标,文字
procedure TForm1.ListBox2DrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
var
AIcon: TIcon;
I, K : Integer;
ARect, BRect: TRect;
H : Integer;
AStyle: TBrushStyle;
begin
try
//计算Item数量
I := ListBox2.Items.Count - 1;
AIcon := TIcon.Create;
//装入图标
ImageList1.GetIcon(0, AIcon);
//填充区域
ListBox2.Canvas.FillRect(Rect);
//计算Rect绘图区的高度
H := Rect.Bottom - Rect.Top;
//如果当前项是Item的最后一项,则在Canvas上没有Item的空白区绘制背景
if Index = I then
begin
K := 1;
ARect := Rect;
//如果当前绘图项的底部小于ListBox2的Canvas的底部,有空白区域
While ARect.Bottom < ListBox2.Canvas.ClipRect.Bottom do
begin
//一次计算下一个绘图区域
ARect.Top := Rect.Top + K * H;
ARect.Bottom := ARect.Top + H;
if (K mod 2 = 0) and (i mod 2 = 1) then
ListBox2.Canvas.stretchDraw(ARect, Image1.Picture.Bitmap)
else if (K mod 2 = 1) and (i mod 2 = 0) then
ListBox2.Canvas.stretchDraw(ARect, Image1.Picture.Bitmap);
inc(K);
end;
end;
//绘制当前项
if Index mod 2 = 1 then
ListBox2.Canvas.stretchDraw(Rect, Image1.Picture.Bitmap);
//绘制图标
ListBox2.Canvas.Draw(Rect.Left, Rect.Top, AIcon);
ARect := Rect;
ARect.Left := Rect.Left + AIcon.Width div 2;
ARect.Top := ARect.top + 2;
//保存当前画笔的风格
AStyle := Listbox2.Canvas.Brush.Style;
//当前选中的Item要填充蓝色背景
if odSelected in State then
begin
ListBox2.Canvas.Brush.Style := bsSolid;
//ListBox2.Canvas.Brush.Color := TColor($00FFB2B5);
//ListBox2.Canvas.RoundRect(Rect.Left + 3, Rect.Top + 3, Rect.Right - 15,
// Rect.Bottom - 3, 5, 5);
Listbox2.Canvas.Brush.Color := clBlue;
//如果当前项拥有焦点,画焦点虚框,当系统再绘制时变成XOR运算从而达到擦除焦点虚框的目的
//if (odFocused in State) then
//DrawFocusRect(Listbox2.Canvas.Handle, Rect);
end
else
begin
//未选中项透明背景,前景色为黑色
ListBox2.Canvas.Brush.Style := bsClear;
Listbox2.Font.Color := clBlack;
end;
//输出文字
ListBox2.Canvas.TextOut(ARect.Left, ARect.top, ListBox2.Items[Index]);
//恢复当前画笔的风格
ListBox2.Canvas.Brush.Style := AStyle;
finally
AIcon.Free;
end;
end;