[英]How to change color of a cell in a Delphi TGrid Firemonkey component?
我以 TGrid 列中的單元格示例為例。 組件選項中沒有顏色屬性。 顏色只能通過代碼訪問。 代碼必須放在 Draw Column Cell 事件中,但是它的代碼是什么? 我嘗試使用與 VCL 組件中相同的過程,但 FMX 中的 Tcanvas 不包含畫筆屬性。 該網站上的其他類似問題僅提供有關如何處理顏色的推測。
有沒有人成功地改變了單元格(或其他組件)的背景顏色?
FMX
框架提供了幾種方法來更改TGrid
背景的外觀。 下面介紹了兩種方法,交替行顏色和每個單元格的顏色。
交替行顏色,可選擇使用樣式
這作為可預設的布爾項存在於名為AlternateRowBackground
的TGrid.Options
屬性中。 默認顏色為淺灰色 ($FFEEEEEE)。 要更改此顏色,您可以添加TStyleBook
或右鍵單擊網格並選擇Edit Custom Style...
或Edit Default Style...
,然后更改網格樣式的Color
屬性gridstyle - alternatingrowbackground
。 這是一個顏色更改為Bisque
的示例:
OnDrawColumnCell
事件中的代碼
這甚至會為網格的每個單元格調用,並提供對繪制單元格背景的完全控制。 事件處理程序的標頭如下所示:
procedure TForm11.Grid1DrawColumnCell(Sender: TObject; const Canvas: TCanvas;
const Column: TColumn; const Bounds: TRectF; const Row: Integer;
const Value: TValue; const State: TGridDrawStates);
為了繪畫,我們需要一個TBrush
,所以我們將一個聲明為局部變量:
var
bgBrush: TBrush;
我們現在准備應用特殊背景繪制的一些場景。 首先是如何讓默認繪圖發生在某些單元格狀態。
if (TGridDrawState.Selected in State) or
(TGridDrawState.Focused in State) then
begin
Grid1.DefaultDrawColumnCell(Canvas, Column, Bounds, Row, Value, State);
Exit;
end;
對於以下內容,我們將需要TBrush
,因此我們創建它並管理其生命周期(在 Windows 平台上):
bgBrush:= TBrush.Create(TBrushKind.Solid, TAlphaColors.White); // default white color
try
//
// following code snippets go in here
//
finally
bgBrush.Free;
end;
接下來,一個不使用樣式繪制交替行背景的示例
if Odd(Row) then
bgBrush.Color := TAlphaColors.MoneyGreen+$202020; // a very light green color
Canvas.FillRect(Bounds, 0, 0, [], 1, bgBrush);
然后是給定列的背景顏色示例
case Column.Index of
0: bgBrush.Color := TAlphaColors.lightBlue;
1: bgBrush.Color := TAlphaColors.MoneyGreen;
end;
Canvas.FillRect(Bounds, 0, 0, [], 1, bgBrush);
最后是一個由數據值決定的背景顏色的例子
if Column.Index = 1 then
if Value.AsOrdinal < 0 then // negative
bgBrush.Color := TAlphaColors.Lightpink
else
bgBrush.Color := TAlphaColors.MoneyGreen;
Canvas.FillRect(Bounds, 0, 0, [], 1, bgBrush);
和示例圖像:
文本的顏色與此答案相同
請看這個例子。 評論中的解釋:
procedure TfrmOperationTab1.strgridHeartbeatsDrawColumnCell(Sender: TObject;
const Canvas: TCanvas; const Column: TColumn; const Bounds: TRectF;
const Row: Integer; const Value: TValue; const State: TGridDrawStates);
var
bgBrush: TBrush;
begin
try
// if a cell contains word 'WARNING' then we want to paint its background in Pink color
if Value.AsString.Contains('WARNING') then
begin
// Create pink brush
bgBrush:= TBrush.Create(TBrushKind.Solid, TAlphaColors.Lightpink);
// Paint the whole area
Canvas.FillRect(Bounds, 0, 0, [], 1, bgBrush);
bgBrush.Free;
end;
finally
end;
// IMPORTANT: let system draw all the other staff. If not called, then you wont see the content of your cell
Column.DefaultDrawCell(Canvas, Bounds, Row, Value, State);
end;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.