解决方法
您可以使用TCanvas.TextRect方法,以及tfCalcRect和tfWordBreak标志:
var lRect : TRect; lText : string; begin lRect.Left := 0; lRect.Right := myWidth; lRect.Top := 0; lRect.Bottom := 0; lText := myLabel.Caption; myLabel.Canvas.TextRect( {var} lRect,//will be modified to fit the text dimensions {var} lText,//not modified,unless you use the "tfModifyingString" flag [tfCalcRect,tfWordBreak] //flags to say "compute text dimensions with line breaks" ); ASSERT( lRect.Top = 0 ); //this shouldn't have moved myLabel.Height := lRect.Bottom; end;
TCanvas.TextRect从Windows API中调用DrawTextEx函数。
tfCalcRect和tfWordBreak标志是Windows API的值DT_CALCRECT和DT_WORDBREAK的delphi包装器。您可以在msdn的DrawTextEx文档中找到有关其效果的详细信息