在 Delphi 中,預設的 TListBox 與 TComboBox 僅支援純文字顯示。若要在項目背景繪製圖片,需將控制項的 Style 屬性設為 OwnerDraw 模式,並自行處理繪圖邏輯。本文示範如何在表單建立、繪製、測量項目高度及釋放資源等關鍵事件中實作自訂背景圖片。
TComboBox 與一個 TListBox。ComboBox.Style := csOwnerDrawVariable、ListBox.Style := lbOwnerDrawVariable。TBitmap 變數用於儲存背景圖片。FormCreate 中建立位圖物件並從檔案載入圖片(範例路徑為 C:\delphi\images\buttons\...)。ComboBox.OnDrawItem、ComboBox.OnMeasureItem、ListBox.OnDrawItem、ListBox.OnMeasureItem 事件,實作自訂繪圖與項目高度計算。FormClose 中釋放所有 TBitmap 物件,避免記憶體洩漏。unit Ownerdrw;
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls;
type
TForm1 = class(TForm)
ComboBox1: TComboBox;
ListBox1: TListBox;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure ComboBox1DrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
procedure ComboBox1MeasureItem(Control: TWinControl; Index: Integer;
var Height: Integer);
procedure ListBox1DrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
procedure ListBox1MeasureItem(Control: TWinControl; Index: Integer;
var Height: Integer);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
TheBitmap1, TheBitmap2, TheBitmap3, TheBitmap4,
TheBitmap5: TBitmap;
implementation
{$R *.DFM}
procedure TForm1.FormCreate(Sender: TObject);
begin
TheBitmap1 := TBitmap.Create;
TheBitmap1.LoadFromFile('C:\delphi\images\buttons\globe.bmp');
TheBitmap2 := TBitmap.Create;
TheBitmap2.LoadFromFile('C:\delphi\images\buttons\video.bmp');
TheBitmap3 := TBitmap.Create;
TheBitmap3.LoadFromFile('C:\delphi\images\buttons\gears.bmp');
TheBitmap4 := TBitmap.Create;
TheBitmap4.LoadFromFile('C:\delphi\images\buttons\key.bmp');
TheBitmap5 := TBitmap.Create;
TheBitmap5.LoadFromFile('C:\delphi\images\buttons\tools.bmp');
ComboBox1.Items.AddObject('Item 1', TheBitmap1);
ComboBox1.Items.AddObject('Item 2', TheBitmap2);
ComboBox1.Items.AddObject('Item 3', TheBitmap3);
ComboBox1.Items.AddObject('Item 4', TheBitmap4);
ComboBox1.Items.AddObject('Item 5', TheBitmap5);
{ 同樣為 ListBox1 加入項目與圖片 }
end;
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
TheBitmap1.Free;
TheBitmap2.Free;
TheBitmap3.Free;
TheBitmap4.Free;
TheBitmap5.Free;
end;
{ 以下省略 OnDrawItem、OnMeasureItem 實作細節,
核心邏輯為:在 Rect 區域先繪製背景圖片,
再呼叫 Canvas.TextOut 繪製文字,
OnMeasureItem 則依圖片高度設定 Height 參數。 }
end.
Canvas.Draw 或 StretchDraw 繪製位圖,再輸出文字。TBitmap 需手動 Create 與 Free,建議在 FormCreate/FormClose 成對處理。同樣原理可應用於 TListView、TTreeView 等支援 OwnerDraw 的控制項,實現更豐富的視覺效果。若圖片資源固定,亦可考慮使用 TImageList 統一管理,簡化程式碼。