在TreeView里面,为什么修改Canvas的字体会没有效果?(问题被自己解决,决定散分,24小时内回复都有分加) (100分)

L

lyco

Unregistered / Unconfirmed
GUEST, unregistred user!
在TreeView里面,为了实现“RichText”的效果,我自己向Canvas上面写字,可是为什么我
在第一次设置了字体之后,后面的所有汉字都是按找第一次设定的字体来写的呢?
我的代码如下:

procedure TForm1.TreeView1advancedCustomDrawItem(Sender: TCustomTreeView;
Node: TTreeNode; State: TCustomDrawState; Stage: TCustomDrawStage;
var PaintImages, DefaultDraw: Boolean);
var
NRect: TRect;
TextPlace: Integer;

procedure DrawText(CurCanvas: TCanvas; TextColor: TColor; TextFontStyles: TFontStyles; Text: WideString;
Top: Integer; var NewTextLeft: Integer);
begin
with CurCanvas do
begin
Font.Color := TextColor;
Font.Style := TextFontStyles;
TextOut(NewTextLeft, NRect.Top, Text);
Inc(NewTextLeft, TextWidth(Text));
end;
end;

begin
if (Stage = cdPostPaint) then
begin
NRect := Node.DisplayRect(True);
TextPlace := NRect.Left;
DrawText(Sender.Canvas, clBlue, [fsBold], '粗体', NRect.Top, TextPlace);
DrawText(Sender.Canvas, clRed, [fsUnderline], '下划线', NRect.Top, TextPlace);
DrawText(Sender.Canvas, clBlue, [fsItalic], ' 斜体', NRect.Top, TextPlace);
end;
end;

其中,内部函数GrawText利用传入的颜色和字体来写传入的字符串,可是,所有的字符串都是按照第一次设定的内容来写的,都是蓝色,粗体,好奇怪啊
谁知道怎么回事吗?
 
好象写字程序应该这样
procedure DrawText(CurCanvas: TCanvas; TextColor: TColor; TextFontStyles: TFontStyles; Text: WideString;
Top: Integer; var NewTextLeft: Integer);
begin
with CurCanvas do
begin
Font.Color :=[];
Font.Color :=[];
Font.Color := TextColor;
Font.Color := TextFontStyles;
TextOut(NewTextLeft, NRect.Top, Text);
Inc(NewTextLeft, TextWidth(Text));
end;
end;

 
unjiang,你的修改好像有点怪怪的哦……
 
是不是这句的原因 ?
if (Stage = cdPostPaint) then
 
写错了,不好意思
好象写字程序应该这样
procedure DrawText(CurCanvas: TCanvas; TextColor: TColor; TextFontStyles: TFontStyles; Text: WideString;
Top: Integer; var NewTextLeft: Integer);
begin
with CurCanvas do
begin
Font.Color :=[];
Font.Style :=[];
Font.Color := TextColor;
Font.Style := TextFontStyles;
TextOut(NewTextLeft, NRect.Top, Text);
Inc(NewTextLeft, TextWidth(Text));
end;
end;

 
unjiang,你给我的两端代码好像是一样的啊……

hotyei因为我并不想自己画树状结构的线条和图标,只是想把字体的颜色改的比较复杂(同一个TreeNode里面有不同字体)。
如果我在cdsPrePaint的方式下写字,那么写的字就会被程序自己的内容覆盖掉,但是如果我把DefaultDraw设为False,它就连树状结构的线条和图标都不画了。所以我用cdsPostPaint的方式,可是字体又不听话,好烦……。
难道为了写自己的字体,就得把整个TreeView的Paint的方法都接管过来不成吗?
 
终于在一个国外的网站把问题解决了,原来这个是TTreeView的Bug,TTCustomTreeView用自己的OnChange方法,把TTreeView的Font的OnChange方法覆盖了。
解决方法是,在TReeView所属的Form里面定义两个函数指针,然后在FormCreate的时候把TreeView的Font.Onchange和Brush.OnChange的指针保存下来,之后每修改Font或Brush的属性一次,就执行保留下来的函数一次,参数就是当前的Font或者Brush,一切就都OK了。

唉,我能不能把分数给回自己呢?
 
多人接受答案了。
 
顶部