设定TStringGrid的DefaultDraw = true,系统自动给表格绘制默认的样式和效果。设定自定义格式前,先填充单元格的背景色,以清除原内容。
procedure TShowDetailForm.GridForwardDrawCell( Sender : TObject; ACol, ARow : Integer; Rect : TRect;
State : TGridDrawState );
const
FixSpace = 3;
var
cellText : string;
i, j, tX, tY : Integer;
txtWidth, txtHeight : Integer;
// interleavingColor : TColor;
begin
// interleavingColor := TStringGrid(Sender).FixedColor;
//
with TStringGrid( Sender ) do
begin
cellText := Cells[ ACol, ARow ].Trim;
txtWidth := Canvas.TextWidth( cellText );
txtHeight := Canvas.TextHeight( cellText );
//
if ACol = 0 then
begin // 第一列
// 设定样式 背景色 字体色
Canvas.Brush.Color := TStyleManager.ActiveStyle.GetStyleColor( scCategoryButtons );
Canvas.FillRect( Rect );
if ARow <> 0 then
begin
// 水平居左 垂直居中
tX := Rect.Left + FixSpace;
tY := Rect.Top + ( Rect.Height - txtHeight ) div 2;
Canvas.Font.Style := [ fsBold ];
Canvas.TextRect( Rect, tX, tY, cellText );
end
else
begin
// 水平居中 垂直居中
tX := Rect.Left + ( Rect.Width - txtWidth ) div 2;
tY := Rect.Top + ( Rect.Height - txtHeight ) div 2;
Canvas.FillRect( Rect );
Canvas.Font.Style := [ fsBold ];
Canvas.TextRect( Rect, tX, tY, cellText );
end;
end
else
begin
// 第一行
if ARow = 0 then
begin
// 水平居中 垂直居中
tX := Rect.Left + ( Rect.Width - txtWidth ) div 2;
tY := Rect.Top + ( Rect.Height - txtHeight ) div 2;
// 填充背景色,清除原内容
Canvas.Brush.Color := TStyleManager.ActiveStyle.GetStyleColor( scCategoryButtons );
Canvas.FillRect( Rect );
Canvas.Font.Style := [ fsBold ];
Canvas.TextRect( Rect, tX, tY, cellText );
end
else // 内容区
begin
// 水平居右 垂直居中
if ACol mod 4 = 0 then
begin
tX := Rect.Left + ( Rect.Width - txtWidth - FixSpace ) div 2;
tY := Rect.Top + ( Rect.Height - txtHeight ) div 2;
Canvas.Font.Style := [ fsBold ];
if Cells[ ACol, ARow ] = CorrectChar then
Canvas.Font.Color := clGreen
else
Canvas.Font.Color := clRed;
end
else
begin
tX := Rect.Left + ( Rect.Width - txtWidth - FixSpace );
tY := Rect.Top + ( Rect.Height - txtHeight ) div 2;
Canvas.Font.Style := [ ];
// Canvas.Font.Color := TStyleManager.ActiveStyle.GetStyleFontColor(sfButtonTextNormal) ;
end;
///
if ( State * [ gdSelected, gdRowSelected ] ) <> [ ] then
Canvas.Brush.Color := TStyleManager.ActiveStyle.GetStyleColor( scButtonFocused )
else
begin
if ( ACol <= 4 ) or ( ( ACol >= 9 ) and ( ACol <= 12 ) ) then
Canvas.Brush.Color := FixedColor // clWebYellowGreen
else
Canvas.Brush.Color := TStyleManager.ActiveStyle.GetStyleColor( scGrid );
end;
//无数据时,居中
if Cells[ACol,ARow].Trim = '-' then
begin
tX := Rect.Left + ( Rect.Width - txtWidth - FixSpace ) div 2;
tY := Rect.Top + ( Rect.Height - txtHeight ) div 2;
end;
// 填充单元格背景色
Canvas.FillRect( CellRect( ACol, ARow ) );
Canvas.TextRect( Rect, tX, tY, cellText );
end;
end;
end;
end;