如何在 TGrid 的单元格中渲染 TBitmap 图像?

问题描述

我正在 TGrid 中呈现数据库表的内容效果很好。现在我想在每一行上显示一个垃圾桶的图像作为删除该行的按钮。 这怎么办?

解决方法

有几种方法可以在网格中绘制图像。在运行时加载图像的情况下,例如从数据库中,我更喜欢使用 OnDrawColumnCell 事件:

procedure TForm1.Grid1DrawColumnCell(Sender: TObject; const Canvas: TCanvas;
  const Column: TColumn; const Bounds: TRectF; const Row: Integer;
  const Value: TValue; const State: TGridDrawStates);
var
  bmp: TBitmap;
begin
  if Column.Name = 'ImageColumn1' then
  begin
    bmp := ImageList1.Bitmap(Bounds.Size,Row mod ImageList1.Count);
    if assigned(bmp) then
    begin
      Grid1.BeginUpdate;
      Canvas.DrawBitmap(bmp,bmp.Bounds,Bounds,1);
      Grid1.EndUpdate;
    end;
  end;
end;

此示例需要一个 ImageList1,其中包含多个预加载的图像。 它将所有图像绘制到名称为 ImageColumn1 的列中。 要从数据库中获取图像,请将行替换为 bmp 访问权限。

21 年 4 月 18 日更新:

如果您只想显示垃圾桶图标或例如状态图标,您可以在表单上放置图像列表。添加 TImageColumnTGlyphColumn(例如作为第 2 列)并将此事件中的图像填充到单元格中:

procedure TForm1.Grid1GetValue(Sender: TObject; const ACol,ARow: Integer;
  var Value: TValue);
begin
  if ACol = 2 then
    Value := ImageList1.Bitmap(Bounds.Size,<NumberOfBitmapWithinImageList>);
end;

对于垃圾桶图标,您可以将删除操作写入以下事件方法:

procedure TForm1.Grid1CellClick(const Column: TColumn; const Row: Integer);
begin
  if Column = ImageColumn1 then
    ShowMessage('Row ' + Row.ToString + ' clicked');
end;
,

在 onDrawColumnCell 事件上试试这个代码

if stgMain.Cells[0,Row] = 'isImage' then begin
  Bounds.Location := PointF(Bounds.Location.X,Bounds.Location.Y + ((Bounds.Height - Bounds.Width) / 2));

  Bounds.Width := Bounds.Width;
  Bounds.Height := Bounds.Width;

  Canvas.Fill.Kind := TBrushKind.Bitmap;
  Canvas.Fill.Bitmap.WrapMode := TWrapMode.TileStretch;

  Canvas.FillRect(Bounds,AllCorners,1);

  Canvas.Fill.Bitmap.Bitmap := FMain.img.Bitmap(Bounds.Size,2);
end;