当前位置: > 编程语言 > Delphi教程 >

第十九章-Delphi自定义部件开发(四)(3)

时间:2011-11-16 | 栏目:Delphi教程 | 点击:

3. 公布Pen和Brush

在缺省情况下,一个Canvas具有一个细的、黑笔和实心的白刷,为了使用户在使用Shape控制时能改变Canvas的这些性质,必须能在设计时提供这些对象;然后在画时使用这些对象,这样附属的Pen或Brush被称为Owned对象。

管理Owned对象需要下列三步:

● 声明对象域

● 声明访问属性

● 初始化Owned对象

⑴ 声明Owned对象域

拥有的每一个对象必须有对象域的声明,该域在部件存在时总指向Owned对象。通常,部件在constructor中创建它,在destructor中撤消它。

Owned对象的域总是定义为私有的,如果要使用户或其它部件访问该域,通常要提供访问属性。

下面的代码声明了Pen和Brush的对象域:

type

TSampleShape=class(TGraphicControl)

private

FPen: TPen;

FBrush: TBrush;

end;

⑵ 声明访问属性

可以通过声明与Owned对象相同类型的属性来提供对Owned对象的访问能力。这给使用部件的开发者提供在设计时或运行时访问对象的途径。

下面给Shape控制提供了访问Pen和Brush的方法

type

TSampleShape=class(TGraphicControl)

private

procedure SetBrush(Value: TBrush);

procedure SetPen(Value: TPen);

published

property Brush: TBrush read FBrush write SetBrush;

property Pen: TPen read FPen write SetPen;

end;

然后在库单元的implementation部分写SetBrush和SetPen方法:

procedure TSampleShape.SetBrush(Value: TBrush);

begin

FBrush.Assign(Value);

end;

procedure TSampleShape.SetPen(Value: TPen);

begin

FPen.Assign(Value);

end;

⑶ 初始化Owned对象

部件中增加了的新对象,必须在部件constructor中建立,这样用户才能在运行时与对象交互。相应地,部件的destructor必须在撤消自身之前撤消Owned对象。

因为Shape控制中加入了Pen和Brush对象,因此,要在constructor中初始化它们,在destructor中撤消它们。

① 在Shape控制的constructor中创建Pen和Brush

constructor TSampleShape.Create(Aowner: TComponent);

begin

inherited Create(AOwner);

Width := 65;

Height := 65;

FPen := TPen.Create;

FBrush := TBrush.Create;

end;

② 在部件对象的声明中覆盖destructor

type

TSampleShape=class(TGraphicControl)

public

construstor.Create(Aowner: TComponent); override;

destructor.destroy; override;

end;

③ 在库单元中的实现部分编写新的destructor

destructor TSampleShape.destroy;

begin

FPen.Free;

FBrush.Free;

inherited destroy;

end;

您可能感兴趣的文章:

相关文章