学用 TStringGrid [9] - OnDrawCell

本例效果图:

学用 TStringGrid [9] - OnDrawCell

unit Unit1;



interface



uses

  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,

  Dialogs, StdCtrls, ExtCtrls, Grids;



type

  TForm1 = class(TForm)

    StringGrid1: TStringGrid;

    Panel1: TPanel;

    Button1: TButton;

    Button2: TButton;

    Button3: TButton;

    Button4: TButton;

    procedure FormCreate(Sender: TObject);

    procedure StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;

      Rect: TRect; State: TGridDrawState);

    procedure Button2Click(Sender: TObject);

    procedure Button1Click(Sender: TObject);

    procedure Button3Click(Sender: TObject);

    procedure Button4Click(Sender: TObject);

  end;



var

  Form1: TForm1;



implementation



{$R *.dfm}



var

  TextFormat: TTextFormat;



procedure TForm1.FormCreate(Sender: TObject);

var

  i,j: Integer;

begin

  with StringGrid1 do

    for i := 0 to ColCount - 1 do

      for j := 0 to RowCount - 1 do

        Cells[i,j] := Format('%d%d',[i,j]);



  StringGrid1.Font.Style := [fsBold];

  StringGrid1.Font.Size := 10;

end;



procedure TForm1.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;

  Rect: TRect; State: TGridDrawState);

var

  str: string;

begin

  Randomize;

  StringGrid1.Canvas.Brush.Color := Random($FFFFFF);

  StringGrid1.Canvas.FillRect(Rect);

  str := StringGrid1.Cells[ACol,ARow];

  StringGrid1.Canvas.TextRect(Rect, str, TextFormat);

end;



procedure TForm1.Button1Click(Sender: TObject);

begin

  Randomize;

  StringGrid1.Font.Color := Random($FFFFFF);

  TButton(Sender).Caption := '字体颜色';

end;



procedure TForm1.Button2Click(Sender: TObject);

begin

  TextFormat := [tfSingleLine, tfCenter, tfVerticalCenter];

  StringGrid1.Refresh;

  TButton(Sender).Caption := '居中对齐';

end;



procedure TForm1.Button3Click(Sender: TObject);

begin

  TextFormat := [tfSingleLine, tfRight, tfVerticalCenter];

  StringGrid1.Refresh;

  TButton(Sender).Caption := '右对齐';

end;



procedure TForm1.Button4Click(Sender: TObject);

begin

  TextFormat := [tfSingleLine, tfLeft, tfVerticalCenter];

  StringGrid1.Refresh;

  TButton(Sender).Caption := '左对齐';

end;



end.


 
   

你可能感兴趣的:(String)