Dom*_*see 13 c# win-universal-app uwp
在WPF中,这可以使用FormattedText,如下所示:
private Size MeasureString(string candidate)
{
var formattedText = new FormattedText(
candidate,
CultureInfo.CurrentUICulture,
FlowDirection.LeftToRight,
new Typeface(this.textBlock.FontFamily, this.textBlock.FontStyle, this.textBlock.FontWeight, this.textBlock.FontStretch),
this.textBlock.FontSize,
Brushes.Black);
return new Size(formattedText.Width, formattedText.Height);
}
Run Code Online (Sandbox Code Playgroud)
但是在UWP中,这个类不再存在了.那么如何在通用Windows平台中计算文本尺寸呢?
Dom*_*see 29
在UWP中,您创建一个TextBlock,设置其属性(如Text,FontSize),然后调用其Measure方法并传入无限大小.
var tb = new TextBlock { Text = "Text", FontSize = 10 };
tb.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
Run Code Online (Sandbox Code Playgroud)
之后,它的DesiredSize属性包含TextBlock将具有的大小.
这是使用 Win2D 的另一种方法:
private Size MeasureTextSize(string text, CanvasTextFormat textFormat, float limitedToWidth = 0.0f, float limitedToHeight = 0.0f)
{
var device = CanvasDevice.GetSharedDevice();
var layout = new CanvasTextLayout(device, text, textFormat, limitedToWidth, limitedToHeight);
var width = layout.DrawBounds.Width;
var height = layout.DrawBounds.Height;
return new Size(width, height);
}
Run Code Online (Sandbox Code Playgroud)
你可以这样使用它:
string text = "Lorem ipsum dolor sit amet";
CanvasTextFormat textFormat = new CanvasTextFormat
{
FontSize = 16,
WordWrapping = CanvasWordWrapping.WholeWord,
};
Size textSize = this.MeasureTextSize(text, textFormat, 320.0f);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4160 次 |
| 最近记录: |