使用Canvas的TextWidth方法, 如果等宽的字体,你可以这样计算:n = labelWidth mod Canvas.TextWidth('W') 如果不等宽的字体,你只能够循环计算,需要事先知道你要显示的字符串: var i:integer; s:string; begin for i = 1 to StrLen do begin if Canvas.TextWidth(Copy(s, 1, i)) > labelWidth then break; end n := i; end;以上代码都是伪码
以上 n = labelWidth mod Canvas.TextWidth('W') 中的 mod 改为 div
看看TLabel的代码,看它是如何计算的(它不是有一个AutoSize的属性么)
看 procedure TCustomLabel.AdjustBounds; const WordWraps: array[Boolean] of Word = (0, DT_WORDBREAK); var DC: HDC; X: Integer; Rect: TRect; AAlignment: TAlignment; begin if not (csReading in ComponentState) and FAutoSize then begin Rect := ClientRect; DC := GetDC(0); Canvas.Handle := DC; DoDrawText(Rect, (DT_EXPANDTABS or DT_CALCRECT) or WordWraps[FWordWrap]); Canvas.Handle := 0; ReleaseDC(0, DC); X := Left; AAlignment := FAlignment; if UseRightToLeftAlignment then ChangeBiDiModeAlignment(AAlignment); if AAlignment = taRightJustify then Inc(X, Width - Rect.Right); SetBounds(X, Top, Rect.Right, Rect.Bottom); end; end; 这段代码...
如果等宽的字体,你可以这样计算:n = labelWidth mod Canvas.TextWidth('W')
如果不等宽的字体,你只能够循环计算,需要事先知道你要显示的字符串:
var
i:integer;
s:string;
begin
for i = 1 to StrLen do begin
if Canvas.TextWidth(Copy(s, 1, i)) > labelWidth then
break;
end
n := i;
end;以上代码都是伪码
procedure TCustomLabel.AdjustBounds;
const
WordWraps: array[Boolean] of Word = (0, DT_WORDBREAK);
var
DC: HDC;
X: Integer;
Rect: TRect;
AAlignment: TAlignment;
begin
if not (csReading in ComponentState) and FAutoSize then
begin
Rect := ClientRect;
DC := GetDC(0);
Canvas.Handle := DC;
DoDrawText(Rect, (DT_EXPANDTABS or DT_CALCRECT) or WordWraps[FWordWrap]);
Canvas.Handle := 0;
ReleaseDC(0, DC);
X := Left;
AAlignment := FAlignment;
if UseRightToLeftAlignment then ChangeBiDiModeAlignment(AAlignment);
if AAlignment = taRightJustify then Inc(X, Width - Rect.Right);
SetBounds(X, Top, Rect.Right, Rect.Bottom);
end;
end;
这段代码...