procedure TForm1.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); VAR vCol, vRow : LongInt; begin vCol := ACol; vRow := ARow; WITH Sender AS TStringGrid, Canvas DO IF vCol = 2 THEN BEGIN //对于第2列设置为居中 SetTextAlign(Handle, TA_CENTER); FillRect(Rect); TextRect(Rect, Rect.RIGHT-DefaultColWidth div 2, Rect.Top+2, Cells[vCol, vRow]); END; end;
procedure TForm1.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);begin With Sender As TStringGrid do begin SetTextAlign(Canvas.Handle,TA_CENTER); Canvas.textrect(rect,rect.Left+DefaultColWidth div 2 ,rect.top+2,StringGrid1.Cells[Acol,Arow]); end; end;
已经解决: begin with StrGrid do begin Canvas.FillRect(Rect); s:=Cells[ACol,ARow]; r:=Rect; DrawText(Canvas.Handle,PChar(s),Length(s),r,DT_CENTER or DT_SINGLELINE or DT_VCENTER); end; end;这样不仅水平居中而且垂直居中。
Rect: TRect; State: TGridDrawState);
VAR
vCol, vRow : LongInt;
begin
vCol := ACol; vRow := ARow;
WITH Sender AS TStringGrid, Canvas DO
IF vCol = 2 THEN BEGIN //对于第2列设置为居中
SetTextAlign(Handle, TA_CENTER);
FillRect(Rect);
TextRect(Rect, Rect.RIGHT-DefaultColWidth div 2, Rect.Top+2,
Cells[vCol, vRow]);
END;
end;
Rect: TRect; State: TGridDrawState);begin
With Sender As TStringGrid do
begin
SetTextAlign(Canvas.Handle,TA_CENTER);
Canvas.textrect(rect,rect.Left+DefaultColWidth div 2 ,rect.top+2,StringGrid1.Cells[Acol,Arow]);
end;
end;
begin
with StrGrid do
begin
Canvas.FillRect(Rect);
s:=Cells[ACol,ARow];
r:=Rect;
DrawText(Canvas.Handle,PChar(s),Length(s),r,DT_CENTER or DT_SINGLELINE or DT_VCENTER);
end;
end;这样不仅水平居中而且垂直居中。