gpt4 book ai didi

delphi - 计算最大字体大小

转载 作者:行者123 更新时间:2023-12-03 15:46:17 25 4
gpt4 key购买 nike

我正在计算最大字体大小,以便 at Text 适合 TCxLabel 的 ClientRect。但我可能无法让它工作。 (见图)

enter image description here

字体太大,thxt没有绘制到正确的位置。

这里是如何重现:

将 tcxLabel 放置在空表单上,并将标签与客户端对齐

添加 FormCreate 和 FormResize 事件:

procedure TForm48.FormCreate(Sender: TObject);
begin
CalculateNewFontSize;
end;

procedure TForm48.FormResize(Sender: TObject);
begin
CalculateNewFontSize;
end;

最后实现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;

有谁知道如何计算字体大小以及如何正确放置文本?

最佳答案

我会使用以下内容:

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;

进行初步估计,然后通过每次增量修改大小来进行微调。这很容易理解和验证正确性,而且非常高效。在典型使用中,代码只会调用 TextWidth 几次。

关于delphi - 计算最大字体大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28669443/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com