Welcome

首页 / 软件开发 / Delphi / 第十九章-Delphi自定义部件开发(四)(4)

第十九章-Delphi自定义部件开发(四)(4)2007-05-07④ 设置Owned对象的属性

处理Pen和Brush对象的最后一步是处理Pen和Brush发生改变时对Shape控制的重画问题。Pen和Brush对象都有OnChange事件,因此能够在Shape控制中声明OnChange事件指向的事件处理过程。

下面给Shape控制增加了该方法并更新了部件的constructor以使Pen和Brush事件指向新方法:

type

TSampleShape = class(TGraphicControl)

published

procdeure StyleChanged(Sender: TObject);

end;

implemintation

constructor TSampleShape.Create(AOwner:TComponent);

begin

inherited Create(AOwner);

Width := 65;

Height := 65;

Fpen := TPen.Create;

FPen.OnChange := StyleChanged;

Fbrush := TBrush.Create;

FBrush.OnChange := StyleChanged;

end;

procedure TSampleShape.StyleChanged(Sender: TObject);

begin

Invalidate(true);

end;

当变化发生时,部件重画以响应Pen或Brush的改变。

4. 怎样画部件图形

图形控制基本要素是在屏幕上画图形的方法。抽象类TGraphicControl定义了名为Paint的虚方法,可以覆盖该方法来画所要的图形。

Shape控制的paint方法需要做:

● 使用用户选择的Pen和Brush

● 使用所选的形状

● 调整座标。这样,方形和圆可以使用相同的Width和Height

覆盖paint方法需要两步:

● 在部件声明中增加Paint方法的声明

● 在implementation部分写Paint方法的实现

下面是Paint方法的声明:

type

TSampleShape = class(TGraphicControl)

protected

procedure Paint; override;

end;

然后,编写Paint的实现:

procedure TSampleShape.Paint;

begin

with Canvas do

begin

Pen := FPen;

Brush := FBrush;

case FShape of

sstRectangle, sstSquare :

Rectangle(0, 0, Width, Height);

sstRoundRect, sstRoundSquare:

RoundRect(0, 0, Width, Height, Width div 4, Height div 4);

sstCircle, sstEllipse :

Ellipse(0, 0, Width, Height);

end;

end;

end;

无论任何控制需要更新图形时,Paint就被调用。当控制第一次出现,或者当控制前面的窗口消失时,Windows会通知控制画自己。也可以通过调用Invalidate方法强制重画,就象StyleChanged方法所做的那样。