将图标从图像列表绘制到列表视图?

Draw the icons to the listview from imagelist?

如何把imagelist中的图标绘制到listview中? 我正在使用此代码更改列表视图中的选择颜色,但它没有图像列表中的图标。

procedure TForm2.ListView1DrawItem(Sender: TCustomListView;
  Item: TListItem; Rect: TRect; State: TOwnerDrawState);
var
x, y, i, w, h: integer;
begin
  with ListView1, Canvas do
  begin

    if odSelected in State then
    begin
      Brush.Color := clRed;
      Pen.Color := clWhite;
    end else
    begin
      Brush.Color := Color;
      Pen.Color := Font.Color;
    end;
    Brush.Style := bsSolid;
    FillRect(rect);
    h := Rect.Bottom - Rect.Top + 1;
    x := Rect.Left + 1;
    y := Rect.Top + (h - TextHeight('Hg')) div 2;
    TextOut(x, y, Item.Caption);
    inc(x, Columns[0].Width);
    for i := 0 to Item.Subitems.Count - 1 do begin
      TextOut(x, y, Item.SubItems[i]);
      w := Columns[i + 1].Width;
      inc(x, w);
    end;
  end;
end;

你也要自己画图。

procedure DrawListViewItem(ListView: TListView; Item: TListItem; Rect: TRect; 
  State: TOwnerDrawState; SelectedBrushColor, SelectedFontColor, BrushColor, FontColor: TColor);
var
  x, y, i, w, h, iw, ih: integer;
begin
  with ListView do
  begin
    if odSelected in State then
    begin
      Canvas.Brush.Color := SelectedBrushColor;
      Canvas.Font.Color := SelectedFontColor;
    end else
    begin
      Canvas.Brush.Color := BrushColor;
      Canvas.Font.Color := FontColor;
    end;
    Canvas.Brush.Style := bsSolid;
    Canvas.FillRect(rect);

    h := Rect.Bottom - Rect.Top + 1;

    if Assigned(SmallImages) then
      begin
        iw := SmallImages.Width;
        ih := SmallImages.Height;
        x := Rect.Left + 1;
        if Item.ImageIndex >= 0 then 
          SmallImages.Draw(Canvas, Rect.Left + x, Rect.Top +(h - ih) div 2, Item.ImageIndex);
        x := x + iw + 2;
      end
    else
      begin
        iw := 0;
        ih := 0;
        x := Rect.Left + 1;
      end;

    y := Rect.Top + (h - Canvas.TextHeight('Hg')) div 2;
    Canvas.TextOut(x, y, Item.Caption);
    inc(x, Columns[0].Width - iw);
    for i := 0 to Item.Subitems.Count - 1 do begin
      Canvas.TextOut(x, y, Item.SubItems[i]);
      w := Columns[i + 1].Width;
      inc(x, w);
    end;
  end;
end;

procedure TForm1.ListView1DrawItem(Sender: TCustomListView; Item: TListItem; Rect: TRect; State: TOwnerDrawState);
begin
  DrawListViewItem(ListView1, Item, Rect, State, clRed, clWhite, ListView1.Color, ListView1.Font.Color);
end;

我已将绘图代码移至单独的函数中。这使得它可以重复使用并且更干净一些。直接在表单方法中使用 with 会产生不需要的副作用。双 with 子句也是如此,所以我只使用了一个(尽管我倾向于在我的代码中完全避免 with)。

我注意到您使用了 Pen.Color,但我将其更改为 Font.Color,因为设置 Pen 对您的代码没有任何影响,我假设您确实想要更改文本的颜色。