如何计算 WPF TextBlock 已知字体大小和字符的宽度? [英] How to calculate WPF TextBlock width for its known font size and characters?

查看:32
本文介绍了如何计算 WPF TextBlock 已知字体大小和字符的宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有 TextBlock 文本 "Some Text"字体大小 10.0.

Let's say I have TextBlock with text "Some Text" and font size 10.0.

如何计算合适的TextBlock 宽度?

推荐答案

使用 FormattedText 类.

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

I made a helper function in my code:

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 布局的与设备无关的像素.

It returns device-independent pixels that can be used in WPF layout.

这篇关于如何计算 WPF TextBlock 已知字体大小和字符的宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆