Author: Tomas Rutkauskas
How to show images in the cells of a TStringGrid
Answer:
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:
1 2 procedure TForm1.StringGridImageSourceDrawCell(Sender: TObject;
3 Col, Row: Integer; Rect: TRect; State: TGridDrawState);
4 var5 Bitmap: TBitmap;
6 Filename: string;
7 begin8 Filename := (Sender as TStringGrid).Cells[Col, Row];
9 if Filename <> NoImagesLoaded then{special "kludge" case}10 begin11 Bitmap := TBitmap.Create;
12 try13 Bitmap.LoadFromFile(Filename);
14 (Sender as TStringGrid).Canvas.StretchDraw(Rect, Bitmap);
15 finally16 Bitmap.Free
17 end;
18 {Draw blue outline around selected row}19 if Row = (Sender as TStringGrid).Row then20 begin21 with (Sender as TStringGrid).Canvas do22 begin23 Pen.Color := clBlue;
24 Pen.Width := 5;
25 MoveTo(Rect.Left + 2, Rect.Top + 2);
26 LineTo(Rect.Right - 2, Rect.Top + 2);
27 LineTo(Rect.Right - 2, Rect.Bottom - 2);
28 LineTo(Rect.Left + 2, Rect.Bottom - 2);
29 LineTo(Rect.Left + 2, Rect.Top + 2)
30 end;
31 end;
32 end;
33 end;
Solve 2:
In your StringGrid's OnDrawCell event handler, place some code that resembles:
34 with (Sender as TStringGrid) do35 with Canvas do36 begin37 {...}38 Draw(Rect.Left, Rect.Top, Image1.Picture.Graphic);
39 {...}40 end;
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.