如何为TStringGrid绘制背景?

6

我使用Delphi的OnDrawCell事件进行TStringGrid的自定义绘图。 单元格覆盖区域没有问题,但是如何绘制最右列右侧和最后一行下方的背景呢?

(编辑) 实际上并不需要绘制,我只想设置用于背景的颜色。 我正在使用XE2并研究VCL样式。 即使在默认绘图中,在stringgrid中设置颜色似乎根本没有任何效果。

TIA


2
好的,我终于找到了。问题在于TStringGrid的DrawingStyle属性默认为gdsThemed。 将其设置为gdsClassic使网格的Color属性生效 - 也适用于背景。 问题解决了。感谢Andreas提供了一种完全控制背景绘画过程的方法,但这对我的问题来说有点过度。问候 TheRoadrunner - TheRoadrunner
1个回答

2

我在Google上找到了这段代码(不是我的,我找不到作者的名字,可能来源于StackExchange...)。它定义了一个从TStringGrid派生出来的类,并实现了新的背景绘制。(该示例使用位图,但您可以轻松更改...)

  type
  TStringGrid = class(Grids.TStringGrid)
  private
    FGraphic: TGraphic;
    FStretched: Boolean;
    function BackgroundVisible(var ClipRect: TRect): Boolean;
    procedure PaintBackground;
  protected
    procedure Paint; override;
    procedure Resize; override;
    procedure TopLeftChanged; override;
  public
    property BackgroundGraphic: TGraphic read FGraphic write FGraphic;
    property BackgroundStretched: Boolean read FStretched write FStretched;
  end;

  TForm1 = class(TForm)
    StringGrid: TStringGrid;
    Image: TImage;
    procedure FormCreate(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

{ TStringGrid }

function TStringGrid.BackgroundVisible(var ClipRect: TRect): Boolean;
var
  Info: TGridDrawInfo;
  R: TRect;
begin
  CalcDrawInfo(Info);
  SetRect(ClipRect, 0, 0, Info.Horz.GridBoundary, Info.Vert.GridBoundary);
  R := ClientRect;
  Result := (ClipRect.Right < R.Right) or (ClipRect.Bottom < R.Bottom);
end;

procedure TStringGrid.Paint;
begin
  inherited Paint;
  PaintBackground;
end;

procedure TStringGrid.PaintBackground;
var
  R: TRect;
begin
  if (FGraphic <> nil) and BackgroundVisible(R) then
  begin
    with R do
      ExcludeClipRect(Canvas.Handle, Left, Top, Right, Bottom);
    if FStretched then
      Canvas.StretchDraw(ClientRect, FGraphic)
    else
      Canvas.Draw(0, 0, FGraphic);
  end;
end;

procedure TStringGrid.Resize;
begin
  inherited Resize;
  PaintBackground;
end;

procedure TStringGrid.TopLeftChanged;
begin
  inherited TopLeftChanged;
  PaintBackground;
end;

{ TForm1 }

procedure TForm1.FormCreate(Sender: TObject);
begin
  // Usage: 
  StringGrid.BackgroundGraphic := Image.Picture.Graphic;
  StringGrid.BackgroundStretched := True;
end;

2
这是来自NGLN在SO上的答案。delphi-stringgrid-with-picture-in-background。它应该与背景图片一起使用。 - LU RD
好的,谢谢!使用该代码在网格上绘制其他背景应该不会有问题。 - Andreas
2
没问题,但是为了回答这个问题,你可以详细说明一下如何绘制背景颜色。 - LU RD
2
@Andreas 你本可以自己添加链接。习惯上,将你重申的信息归属于其来源是很常见的。 - Marjan Venema
@LU RD:问题已经被编辑过了。一开始并没有暗示只需要绘制背景的颜色。 - Andreas
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接