begin
if FShape<>value then
begin
FShape := value;
Invalidate(True); { 强制新形状的重画 }
end;
end;
2. 覆盖constructor和destructor
为了改变缺省属性值和初始化部件拥有的对象,需要覆盖继承的constructor和destructor方法。
图形控制的缺省大小是相同的,因此需要改变Width和Height属性。
本例中Shape控制的大小的初始设置为边长65个象素点。
⑴
在部件声明中增加覆盖constructor
type
TSampleShape=class(TGraphicControl)
public
constructor Create(Aowner: TComponent); override;
end;
⑵
用新的缺省值重新声明属性Height和width
type
TSampleShape=class(TGrahicControl)
published
property Height default 65;
property Width default 65;
end;
⑶
在库单元的实现部分编写新的constructor
constructor TSampleShape.Create(Aowner: TComponent);
begin
inherited Create(AOwner);
width := 65;
Height := 65;
end;
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;
上一页 [1] [2] [3] 下一页
|