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

时间:2015-01-02 07:08:56

标签: delphi listview delphi-7

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

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;

1 个答案:

答案 0 :(得分:4)

你也必须自己画画。

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对您的代码没有任何影响,我认为您确实想要更改文字的颜色。