Delphi:如何在CustomDrawItem的List View中绘制小图标

max*_*fax 0 delphi graphics listview draw

如何扩展此代码:ListView在vsReport模式下着色项目和行来绘制小图标?

如果我有3列,为什么会出现错误'List index out of bounds(2)'?

谢谢!

And*_*and 5

有很多方法可以绘制图标,具体取决于它们来自哪里(文件,资源,系统图标等),取决于是否应该为所有项目设置单个图标,或者每个项目是否都有自己的图标.无论如何,从上一个问题的代码的扩展版本中可以清楚一般的想法(我也修复了越界错误......):

type
  TForm1 = class(TForm)
  ...
  private
    { Private declarations }
    bm: TBitmap;
  ...
  end;

...

implementation

...

procedure TForm1.FormCreate(Sender: TObject);
begin
  bm := TBitmap.Create;
  bm.LoadFromFile('C:\Users\Andreas Rejbrand\Desktop\img.bmp');
end;

procedure TForm1.ListView1DrawItem(Sender: TCustomListView; Item: TListItem;
  Rect: TRect; State: TOwnerDrawState);
var
  i: Integer;
  x1, x2: integer;
  r: TRect;
  S: string;
const
  DT_ALIGN: array[TAlignment] of integer = (DT_LEFT, DT_RIGHT, DT_CENTER);
begin
  if Odd(Item.Index) then
  begin
    Sender.Canvas.Font.Color := clBlack;
    Sender.Canvas.Brush.Color := $F6F6F6;
  end
  else
  begin
    Sender.Canvas.Font.Color := clBlack;
    Sender.Canvas.Brush.Color := clWhite;
  end;
  Sender.Canvas.Brush.Style := bsSolid;
  Sender.Canvas.FillRect(Rect);
  x1 := 0;
  x2 := 0;
  r := Rect;
  Sender.Canvas.Brush.Style := bsClear;
  Sender.Canvas.Draw(3, r.Top + (r.Bottom - r.Top - bm.Height) div 2, bm);
  for i := 0 to ListView1.Columns.Count - 1 do
  begin
    inc(x2, ListView1.Columns[i].Width);
    r.Left := x1;
    r.Right := x2;
    if i = 0 then
    begin
      S := Item.Caption;
      r.Left := bm.Width + 6;
    end
    else
      S := Item.SubItems[i - 1];
    DrawText(Sender.Canvas.Handle,
      S,
      length(S),
      r,
      DT_SINGLELINE or DT_ALIGN[ListView1.Columns[i].Alignment] or
        DT_VCENTER or DT_END_ELLIPSIS);
    x1 := x2;
  end;
end;
Run Code Online (Sandbox Code Playgroud)

截图http://privat.rejbrand.se/TListViewCustomDrawIcon.png

  • 我想我应该得到我用pbrush制作的那个很棒的图标奖. (5认同)
  • `TImageList.Draw()`将是在此代码中绘制图像的另一种常用方法 (3认同)