使用C++Buider制作自繪畫(huà)列表框

字號(hào):

C++ Builder中的列表框和組合框控件都已經(jīng)提供了自繪畫(huà)接口。使用這些接口可以實(shí)現(xiàn)把列表框和組合框中的項(xiàng)目顯示為圖像。如果把這種功能封裝成組件就更妙了,下面以列表框?yàn)槔痉哆@一過(guò)程。
    一 實(shí)現(xiàn)原理
    列表框有的Style屬性定義了三種風(fēng)格,lbStandard風(fēng)格只能顯示文本,bOwner-DrawFixed與lbOwnerDrawVariable風(fēng)格可以實(shí)現(xiàn)自繪畫(huà)功能,所不同的是,具有前者風(fēng)格的列表框中每一項(xiàng)的高度都是相同的,后者允許應(yīng)用程序?yàn)槊恳豁?xiàng)定義不同高度。
    具有自繪畫(huà)風(fēng)格的列表框,在列表框的外觀改變的時(shí)候,如增加,刪除,滾動(dòng)項(xiàng)目,總要觸發(fā)兩個(gè)事件句柄:
    TMeasureItemEvent OnMeasureItem;
    TDrawItemEvent OnDrawItem;
    typedef void __fastcall (_closure *TDrawItemEvent)(TWinControl* Control,int Index,Trect& Rect; TOwnerDrawState State);
    typedef void __fastcall(_closure* TMeasureItemEvent)(TWinControl* Control, int Index,int& Height);
    OnMeasureItem事件傳遞一個(gè)參數(shù)Height,應(yīng)用程序需要填寫(xiě)一項(xiàng)來(lái)決定這一項(xiàng)的高度,如果沒(méi)有改變,則使用列表框的ItemHeight的值。lbOwnerDrawFixed風(fēng)格的列表框不觸發(fā)這一事件,故它使用自身的ItemHeight。OnDrawItem傳遞的Rect表示可在上作畫(huà)的矩形區(qū),程序可以使用列表框Canvas屬性來(lái)畫(huà)圖。
    二 示例
    1 在IDE環(huán)境中,選擇“File-New”,在對(duì)話(huà)框中雙擊“Component”,出現(xiàn)"New Component"對(duì)話(huà)框,在Ancestor Type中選擇“TCustomListBox",在Class Name中輸入"TImageListBox",點(diǎn)Create Uints,就生成一個(gè)類(lèi)框架。
    2 在頭文件(ImageListBox.h)中的相應(yīng)域中,增加下列成員:
    private:
    Graphics::Tgraphic* tmpGraphic;
    protected:
    void __fastcall MyDrawItem(TWinControl *Control,int Index, const Trect &Rect,TOwnerDrawState State);
    void __fastcall MyMeasureItem(TWinControl *Control,int Index, int &Height);
    public:
    __fastcall TImageListBox(Tcomponent* Owner);
    __fastcall ~TImageListBox();
    void __fastcall AddImage(System::AnsiString Filename,System::AndiString* String);
    …