Imagen de fondo en un StringGrid

2800 vistas

Veamos el código a usar para poner una imagen de fondo de las celdas blancas de un TStringGrid. La imagen tiene que estar en un Bitmap, pero pudiendo estar perfectamente en un TImage. El procedimiento controla el desplazamiento del fondo de la imagen si se usan las barras de desplazamiento:



delphi
  1. procedure TForm1.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
  2.   Rect: TRect; State: TGridDrawState);
  3. var
  4.   i, j, x, y: Integer;
  5.   R: TRect;
  6. begin
  7.   with Sender as TStringGrid do With Canvas do
  8.   begin
  9.     if gdFixed in State then
  10.     begin
  11.       { Las celdas grises siempre se pintan en gris }
  12.       Brush.Color := clBtnFace;
  13.       Brush.Style := bsSolid;
  14.       FillRect(Rect);
  15.     end
  16.     else
  17.     begin
  18.       if gdSelected in State then
  19.       begin
  20.         { las celdas seleccionadas van en azul }
  21.         Brush.Color := clNavy;
  22.         Brush.Style := bsSolid;
  23.         FillRect(Rect);
  24.       end
  25.       else
  26.       begin
  27.         { buscamos la zona de la imagen a copiar para tener en cuenta el uso de las barras de desplazamiento }
  28.         x := 0;
  29.         for i := FixedCols + 1 to ACol do Inc(x, ColWidths [i]);
  30.         y := 0;
  31.         for i := FixedRows + 1 to ARow do Inc(y, RowHeights[i]);
  32.         R.Lef := x;
  33.         R.Right := x + Rect.Right - Rect.Left;
  34.         R.Top := y;
  35.         R.Bottom := y + Rect.Bottom - Rect.Top;
  36.         { dibujamos una parte de la imagen }
  37.         CopyRect(Rect, MiBitmap.Canvas, R);
  38.         Brush.Style := bsClear;
  39.       End;
  40.     End;
  41.  
  42.     { Selección del color del texto }
  43.     if gdSelected in State then
  44.       SetTextColor(Canvas.Handle, clWhite)
  45.     else SetTextColor(Canvas.Handle, clBlack);
  46.  
  47.     { dibujamos el texto usando el API }
  48.     DrawText(Canvas.Handle, PChar(Cells[ACol,ARow]), -1, Rect ,DT_NOPREFIX );
  49.   End;
  50. end;



MiBitMap es un objeto de tipo TBitMap que tiene que haber sido cargado con la imagen. La imagen tiene que ser suficientemente grande como para cubrir todo el fondo del TStringGrid.