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

假设我的TextBlock文字为“ Some Text”字体大小为10.0

如何计算合适的TextBlock 宽度


呼如林
浏览 2024回答 3
3回答

富国沪深

作为记录...我假设操作者正在尝试以编程方式确定将textBlock添加到可视树后将占用的宽度。IMO比formattedText(如何处理诸如textWrapping之类的格式)更好的解决方案是在示例TextBlock上使用Measure和Arrange。例如var textBlock = new TextBlock { Text = "abc abd adfdfd", TextWrapping = TextWrapping.Wrap };// auto sizedtextBlock.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));textBlock.Arrange(new Rect(textBlock.DesiredSize));Debug.WriteLine(textBlock.ActualWidth); // prints 80.323333333333Debug.WriteLine(textBlock.ActualHeight);// prints 15.96// constrain the width to 16textBlock.Measure(new Size(16, Double.PositiveInfinity));textBlock.Arrange(new Rect(textBlock.DesiredSize));Debug.WriteLine(textBlock.ActualWidth); // prints 14.58Debug.WriteLine(textBlock.ActualHeight);// prints 111.72

神不在的星期二

使用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布局中使用的与设备无关的像素。
打开App,查看更多内容
随时随地看视频慕课网APP