2009. május 4., hétfő

Show images in the cells of a TStringGrid


How to show images in the cells of a TStringGrid


Solve 1:

The following example uses a TStringGrid to display the bitmaps from the filename strings stored in each cell. In the TStringGrid, I set the DefaultRowHeight to 96 and the DefaultColWidth to 128 (with ColCount = 1).

Here's the OnDrawCell that does all the work:

procedure TForm1.StringGridImageSourceDrawCell(Sender: TObject;
  Col, Row: Integer; Rect: TRect; State: TGridDrawState);
  Bitmap: TBitmap;
  Filename: string;
  Filename := (Sender as TStringGrid).Cells[Col, Row];
  if Filename <> NoImagesLoaded then {special "kludge" case}
    Bitmap := TBitmap.Create;
      (Sender as TStringGrid).Canvas.StretchDraw(Rect, Bitmap);
    {Draw blue outline around selected row}
    if Row = (Sender as TStringGrid).Row then
      with (Sender as TStringGrid).Canvas do
        Pen.Color := clBlue;
        Pen.Width := 5;
        MoveTo(Rect.Left + 2, Rect.Top + 2);
        LineTo(Rect.Right - 2, Rect.Top + 2);
        LineTo(Rect.Right - 2, Rect.Bottom - 2);
        LineTo(Rect.Left + 2, Rect.Bottom - 2);
        LineTo(Rect.Left + 2, Rect.Top + 2)

Solve 2:

In your StringGrid's OnDrawCell event handler, place some code that resembles:

with (Sender as TStringGrid) do
  with Canvas do
    Draw(Rect.Left, Rect.Top, Image1.Picture.Graphic);

Using the Draw() or StretchDraw() method of TCanvas should do the trick. BTW, Image1 above is a TImage with a bitmap already loaded into it.

Nincsenek megjegyzések:

Megjegyzés küldése