在Delphi的DrawGrid中绘制TBitmaps

在Delphi的DrawGrid中绘制TBitmaps,delphi,gridview,bitmap,Delphi,Gridview,Bitmap,我在Delphi XE5中有一个8 x 16的绘图网格,我想用我存储在C:\Users\Sean Ewing\Documents\My Documents\Delphi Tutorials\Other\Math-O-Sphere\Win32\Debug\img中的九个图像随机填充它。我目前正在尝试加载一个图像,以确保我的操作正确。下面是我用来执行此操作的代码: procedure TForm1.grdPlayFieldDrawCell(Sender: TObject; ACol, ARo

我在Delphi XE5中有一个8 x 16的绘图网格,我想用我存储在C:\Users\Sean Ewing\Documents\My Documents\Delphi Tutorials\Other\Math-O-Sphere\Win32\Debug\img中的九个图像随机填充它。我目前正在尝试加载一个图像,以确保我的操作正确。下面是我用来执行此操作的代码:

    procedure TForm1.grdPlayFieldDrawCell(Sender: TObject; ACol, ARow: Integer;
     Rect: TRect; State: TGridDrawState);
      var
        spherePlus: TBitmap;

      begin
        spherePlus.LoadFromFile(ExtractFilePath(Application.ExeName) + '\img\Sphere +1.bmp');
        grdPlayField.Canvas.Draw(0, 0, spherePlus);
      end;

代码编译得很好,根据我在Embarcadero wiki中读到的内容,这是正确的,但在运行时加载DrawGgrid时,我遇到了一个错误。哪里出错了?

您需要先创建位图,然后才能使用它:

procedure TForm1.grdPlayFieldDrawCell(Sender: TObject; ACol, ARow: Integer;
 Rect: TRect; State: TGridDrawState);
  var
    spherePlus: TBitmap;
  begin
    spherePlus := TBitmap.Create;
    try
      spherePlus.LoadFromFile(ExtractFilePath(Application.ExeName) + 
          '\img\Sphere +1.bmp');
      grdPlayField.Canvas.Draw(0, 0, spherePlus);
    finally
      spherePlus.Free;
    end;
  end;
您还应该注意,事件中接收到的
Rect
参数是需要绘制的区域,因此您需要使用
Canvas.StretchDraw
并将该矩形传递给它。它对当前问题没有帮助,但当您进入下一步时,您将需要它。您可以识别使用
ACol
ARow
参数绘制的确切单元格,因此您可以使用该信息加载列的特定图像,或输出列或行的文本

// Load specific image for the cell passed in ACol and ARow,
// and then draw it to the appropriate area using the Rect provided.
grdPlayField.Canvas.StretchDraw(Rect, spherePlus);

您忘记了
spherePlus:=TBitmap.Create
。你有AV,对吗?当你问问题时,不要忘记告诉你得到了什么错误,在哪里。只加载一次位图。不是每次你都要画画。