【问题标题】:WPF Formatted Text : Calculate font size to fill available height spaceWPF 格式化文本:计算字体大小以填充可用高度空间
【发布时间】:2023-04-11 03:52:02
【问题描述】:

这是我的FormattedText,它是画布的孩子:

             this.formattedText = new FormattedText(
                                "This is a text to test",
                                CultureInfo.CurrentUICulture,
                                this.FlowDirection,
                                new Typeface(this.FontFamily, this.FontStyle, this.FontWeight, FontStretches.Normal),
                                this.FontSize,
                                Fill);

请看这张图片:

第三种形式是我想要的, 但我不知道如何计算字体大小以适应高度(不是宽度), 因为不同的字体有不同的高度,不同的FontFamily.LineSpacing。

注意:我不想使用ViewBox,因为我想将文本动画化为抓取文本和股票代码。

更新:

有些字体需要对FontSize以上的高度进行控制,这取决于FontFamily.LineSpacing。我可以通过设置LineHeight 来去掉上面的空格,但是我不能根据FontFamily.LineSpacing 计算新的FontSize。

请帮帮我。

【问题讨论】:

  • hmm..您是否尝试将formattedText 字体大小设置为this.height? this.formattedText = new FormattedText( "This is a text to test", CultureInfo.CurrentUICulture, this.FlowDirection, new Typeface(this.FontFamily, this.FontStyle, this.FontWeight, FontStretches.Normal), this.Height, Fill);
  • 是的,我还将FontSize 设置为父高度。但问题是空间较小。 (有些字体需要大于控制高度的大小,这取决于FontFamily.LineSpacing。我可以通过设置LineHeight 来移除上部空间,但我无法计算新的FontSize 来移除下部空间。

标签: c# wpf font-size formatted-text


【解决方案1】:

您可以使用循环来获取最大字体大小(步长 1):

int MaxFontSize = 0;
FormattedText Ft = ... //Your formatted text
while(true)
{
  Ft.SetFontSize(MaxFontSize);
  if (Ft.Height > MaxHeigthOfControl)
  {
    //Too large! Maxmimum size found one step before
    MaxFontSize--;
    break;
  }
  else
  {
    MaxFontSize++;
  }
}
//MaxFontSize is the maximum possible FontSize

如果这种增量方式要减慢...尝试使用如下图所示的近似值来实现:

【讨论】:

  • 感谢您的重播,我也设置了最大可能FontSize,但问题是有上下空间。设置LineHeight可以去掉上面的空格,但是不能去掉下面的空格。
【解决方案2】:

好的,你要明白 FormattedText 控件比你想象的要复杂。

有一个LineHeight、BaseLine 和TextAlignment 属性会影响您感兴趣的布局区域。尝试更改这些属性以获得您需要的内容

【讨论】:

  • 感谢您的重播,但我使用LineHeight 删除了上部空间(如图所示),BaseLine 是只读的,TextAlignment 属性不受影响。
猜你喜欢
  • 2011-01-17
  • 2013-08-03
  • 2021-03-10
  • 2012-10-01
  • 2012-02-07
  • 1970-01-01
  • 1970-01-01
  • 2022-08-19
  • 1970-01-01
相关资源
最近更新 更多