为了账号安全,请及时绑定邮箱和手机立即绑定

如何计算WPF TextBlock的已知字体大小和字符宽度?

如何计算WPF TextBlock的已知字体大小和字符宽度?

C#
呼如林 2019-11-12 11:02:40
假设我的TextBlock文字为“ Some Text”,字体大小为10.0。如何计算合适的TextBlock 宽度?
查看完整描述

3 回答

?
富国沪深

TA贡献1790条经验 获得超9个赞

作为记录...我假设操作者正在尝试以编程方式确定将textBlock添加到可视树后将占用的宽度。IMO比formattedText(如何处理诸如textWrapping之类的格式)更好的解决方案是在示例TextBlock上使用Measure和Arrange。例如


var textBlock = new TextBlock { Text = "abc abd adfdfd", TextWrapping = TextWrapping.Wrap };

// auto sized

textBlock.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));

textBlock.Arrange(new Rect(textBlock.DesiredSize));


Debug.WriteLine(textBlock.ActualWidth); // prints 80.323333333333

Debug.WriteLine(textBlock.ActualHeight);// prints 15.96


// constrain the width to 16

textBlock.Measure(new Size(16, Double.PositiveInfinity));

textBlock.Arrange(new Rect(textBlock.DesiredSize));


Debug.WriteLine(textBlock.ActualWidth); // prints 14.58

Debug.WriteLine(textBlock.ActualHeight);// prints 111.72


查看完整回答
1 反对 回复 2019-11-12
?
神不在的星期二

TA贡献1963条经验 获得超6个赞

使用FormattedText该类。


我在代码中做了一个辅助函数:


private Size MeasureString(string candidate)

{

    var formattedText = new FormattedText(

        candidate,

        CultureInfo.CurrentCulture,

        FlowDirection.LeftToRight,

        new Typeface(this.textBlock.FontFamily, this.textBlock.FontStyle, this.textBlock.FontWeight, this.textBlock.FontStretch),

        this.textBlock.FontSize,

        Brushes.Black,

        new NumberSubstitution(),

        1);


    return new Size(formattedText.Width, formattedText.Height);

}

它返回可在WPF布局中使用的与设备无关的像素。


查看完整回答
反对 回复 2019-11-12
  • 3 回答
  • 0 关注
  • 2022 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信