加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

delphi – 计算最大字体大小

发布时间:2020-12-15 09:07:14 所属栏目:大数据 来源:网络整理
导读:我正在计算最大字体大小,以便Text适合TCxLabel的ClientRect.但我可能无法让它工作. (见图) fontsize是大而且thxt没有绘制到正确的位置. 这里如何重现: 将tcxLabel放在空窗体上,并将标签对齐到客户端 添加FormCreate和FormResize事件: procedure TForm48.Fo
我正在计算最大字体大小,以便Text适合TCxLabel的ClientRect.但我可能无法让它工作. (见图)

fontsize是大而且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;

有没有人知道如何计算字体大小和ho正确放置文本?

解决方法

我会沿着这些方向使用一些东西:

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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读