我正在使用 Avalonia 11.1,我想在实际渲染之前知道我的
TextBlock
内容的大小,以便我可以一次性正确对齐组件。
我找不到任何专用于该功能的现成函数或文档。我尝试创建一个
TextBlock
并调用其 Measure
方法,但宽度返回 0。
有(相对)简单的方法吗?
TL;博士
public static Size CalculateTextSize(string myText, string myFontResourceKey, int myFontSize)
{
if (Application.Current?.TryFindResource(myFontResourceKey, out object? fontObj) != true)
{
throw new ArgumentException($"Cannot find a resource named {myFontResourceKey} in this application's resources.");
}
if (!(fontObj is FontFamily myFont))
throw new ArgumentException($"The resource {myFontResourceKey} is not a FontFamily.");
var ts = TextShaper.Current;
var typeface = new Typeface(myFont);
ShapedBuffer shaped = ts.ShapeText(myText, new TextShaperOptions(typeface.GlyphTypeface, myFontSize));
var run = new ShapedTextRun(shaped, new GenericTextRunProperties(typeface, myFontSize));
return run.Size;
}
############
在我撰写本文时,https://reference.avaloniaui.net/api/ 上的 API 参考似乎仍以 11.0 版为目标。
Avalonia.Media.TextFormatting
命名空间包含一堆与测量文本相关的类,但它们与版本11.1略有不同。
经过一番尝试和错误,我终于成功了:
ResourceDictionary
xaml 文件中定义的,唯一可以检索它的函数是 StyledElement.FindResource
。可以使用 Application.Current.FindResource("MyFontResourceKey", out object? fontObj);
FontFamily
TypeFace
创建
FontFamily
TextShaper
实例ShapedBuffer
获取一个
GlyphRun
(在 avalonia 11.0 中似乎名为
TextShaper
ShapedTextRun
ShapedTextRun.Size
属性获取渲染文本的大小。如果我错过了一些更简单的事情,请毫不犹豫地回答!