設定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;