1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69: 70: 71: 72: 73: 74: 75: 76:
| type TWrapRecord=record Height:Integer; Lines: array of string; end;
function WrapText(Canvas:TCanvas; Text:string; const MaxWidth:integer):TWrapRecord; var S:string; CurrWidth:integer; begin SetLength(Result.Lines,0); Result.Height:=0; CurrWidth:=MaxWidth; Text:=Text+' '; repeat S:=copy(Text,1,pos(' ',Text)-1); Delete(Text,1,pos(' ',Text));
if (Canvas.TextWidth(S+' ')+CurrWidth)<=MaxWidth then begin with Result do Lines[High(Lines)]:=Lines[High(Lines)] + ' ' +S; Inc(CurrWidth, Canvas.TextWidth(S+' ')); end else with Result do begin if length(Lines)>0 then Inc(Height,Canvas.TextHeight(Lines[High(Lines)]));
SetLength(Lines,length(Lines)+1); Lines[High(Lines)]:=S; CurrWidth:=Canvas.TextWidth(S); end; until length(TrimRight(Text))=0;
with Result do Inc(Height,Canvas.TextHeight(Lines[High(Lines)])); end;
procedure TForm1.ListBoxMeasureItem(Control: TWinControl; Index: Integer; var Height: Integer); var WrapRecord:TWrapRecord; begin with Control as TListBox do begin Canvas.Font.Assign(Font); WrapRecord:=WrapText(Canvas,Items[Index],ClientWidth); if WrapRecord.Height<ItemHeight then WrapRecord.Height:=ItemHeight; end; Height:=WrapRecord.Height; end;
procedure TForm1.ListBoxDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); var WrapRecord:TWrapRecord; i,y:integer; begin with Control as TListBox do begin Canvas.Font.Assign(Font); Canvas.FillRect(Rect);
WrapRecord:=WrapText(Canvas,Items[Index],ClientWidth); y:=Rect.Top; for i:=Low(WrapRecord.Lines) to High(WrapRecord.Lines) do begin Canvas.TextOut(Rect.Left,y,WrapRecord.Lines[i]); Inc(y,Canvas.TextHeight(WrapRecord.Lines[i])); end; end; end;
procedure TForm1.FormCreate(Sender: TObject); begin ListBox1.OnMeasureItem:=ListBoxMeasureItem; ListBox1.OnDrawItem:=ListBoxDrawItem; ListBox1.Style:=lbOwnerDrawVariable; end; |