计算最大字体大小 [英] Calculate Max Font size
问题描述
我正在尝试计算最大字体大小,以使at文本适合TCxLabel的ClientRect。但是我可能无法正常工作。 (参见图片)
I'm tyring calculate the maximum fontsize in order for at Text to fit into the ClientRect of a TCxLabel. But I cant get it to work probably. (See picture)
字体大小较大,并且未在相应位置绘制thxt。
The fontsize is to big and the thxt is not drawn the corrent place.
此处是如何重现:
将tcxLabel放在一个空的Form上,并将标签贴标签给客户端
Place a tcxLabel on an empty Form, and allign the label to client
添加一个FormCreate和FormResize事件:
Add a FormCreate and a FormResize event :
procedure TForm48.FormCreate(Sender: TObject);
begin
CalculateNewFontSize;
end;
procedure TForm48.FormResize(Sender: TObject);
begin
CalculateNewFontSize;
end;
并最终实现CalculateNewFontSize:
and Finally implement CalculateNewFontSize :
数学;
procedure TForm48.CalculateNewFontSize;
var
ClientSize, TextSize: TSize;
begin
ClientSize.cx := cxLabel1.Width;
ClientSize.cy := cxLabel1.Height;
cxLabel1.Style.Font.Size := 10;
TextSize := cxLabel1.Canvas.TextExtent(Text);
if TextSize.cx * TextSize.cx = 0 then
exit;
cxLabel1.Style.Font.Size := cxLabel1.Style.Font.Size * Trunc(Min(ClientSize.cx / TextSize.cx, ClientSize.cy / TextSize.cy) + 0.5);
end;
有人知道如何计算字体大小并正确放置文本吗?
Does any one know how to calculate the font size and ho to place the text correctly?
推荐答案
我将使用以下方式:
function LargestFontSizeToFitWidth(Canvas: TCanvas; Text: string;
Width: Integer): Integer;
var
Font: TFont;
FontRecall: TFontRecall;
InitialTextWidth: Integer;
begin
Font := Canvas.Font;
FontRecall := TFontRecall.Create(Font);
try
InitialTextWidth := Canvas.TextWidth(Text);
Font.Size := MulDiv(Font.Size, Width, InitialTextWidth);
if InitialTextWidth < Width then
begin
while True do
begin
Font.Size := Font.Size + 1;
if Canvas.TextWidth(Text) > Width then
begin
Result := Font.Size - 1;
exit;
end;
end;
end;
if InitialTextWidth > Width then
begin
while True do
begin
Font.Size := Font.Size - 1;
if Canvas.TextWidth(Text) <= Width then
begin
Result := Font.Size;
exit;
end;
end;
end;
finally
FontRecall.Free;
end;
end;
进行初始估算,然后通过每次递增1来修改大小来进行微调。这很容易理解和验证正确性,而且非常有效。在典型的用法中,代码只会调用几次 TextWidth
。
Make an initial estimate, and then fine tune by modifying the size by increments of one at a time. This is easy to understand and verify for correctness, and also quite efficient. In typical use the code will call TextWidth
only a handful of times.
这篇关于计算最大字体大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!