Centrar el texto en las celdas

3669 vistas

El código siguiente permite centrar el texto en las celdas de un TStringGrid. El centraje es a la vez horizontal y vertical. Para ello usaremos el API de Windows devido a que la función TextOut del Canvas del componente no permite hacer centrados de texto.



delphi
  1. procedure TForm1.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
  2.   Rect: TRect; State: TGridDrawState);
  3. begin
  4.   with Sender as TStringGrid do with Canvas do
  5.   begin
  6.     { selección del color de fondo }
  7.     if gdFixed in State then Brush.Color := clBtnFace
  8.     else
  9.       if gdSelected in State then Brush.Color := clNavy
  10.       else Brush.Color := clWhite;
  11.  
  12.     { dibujado del fondo }
  13.     FillRect(Rect);
  14.  
  15.     { selección del color de texto }
  16.     if gdSelected in State then
  17.       SetTextColor(Canvas.Handle, clWhite)
  18.     else SetTextColor(Canvas.Handle, clBlack);
  19.  
  20.     { dibujado del texto usando el API }
  21.     DrawText(Canvas.Handle, PChar(Cells[ACol,ARow]), -1, Rect ,
  22.               DT_CENTER or DT_NOPREFIX or DT_VCENTER or DT_SINGLELINE  );
  23.   end;
  24. end;



Una variante a este código nos permitirá escribir el texto en varias líneas:



delphi
  1. procedure TForm1.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
  2.   Rect: TRect; State: TGridDrawState);
  3. begin
  4.   with Sender as TStringGrid do with Canvas do
  5.   begin
  6.     { selección del color de fondo }
  7.     if gdFixed in State then
  8.       Brush.Color := clBtnFace
  9.     else
  10.       if gdSelected in State then
  11.         Brush.Color := clNavy
  12.       else Brush.Color := clWhite;
  13.  
  14.     { dibujado del fondo }
  15.     FillRect(Rect);
  16.  
  17.     { selección del color de texto }
  18.     if gdSelected in State then
  19.       SetTextColor(Canvas.Handle, clWhite)
  20.     else SetTextColor(Canvas.Handle, clBlack);
  21.  
  22.     { dibujado del texto usando el API }
  23.     DrawText(Canvas.Handle, PChar(Cells[ACol,ARow]), -1, Rect ,
  24.               DT_CENTER or DT_NOPREFIX or DT_WORDBREAK );
  25.   end;
  26. end;