【发布时间】:2019-04-22 21:33:44
【问题描述】:
我需要一种可靠的方法来获取 RichTextBlock 中包含的文本的高度,甚至在它实际绘制在场景上之前。
使用普通的 Measure() 方法会产生一个奇怪的结果,这可以在 MVCE 中看到:https://github.com/cghersi/UWPExamples/tree/master/MeasureText(我想保持固定宽度,并测量最终高度,但 DesiredSize 的结果大不相同从实际高度!!)。
出于这个原因,我找到了一个粗略的方法(这里提到了https://stackoverflow.com/a/45937298/919700),我扩展了它以达到我的目的,我们使用一些 Win2D API 来计算内容高度。
问题在于,在某些情况下,此方法提供的高度小于预期的高度。
- 是否有一种通用的方法来检索(正确的)高度 TextBlock,甚至在它被绘制在场景中之前?
- 如果不是这样,我做错了什么?
这是我的代码(您也可以在此处找到 MVCE:https://github.com/cghersi/UWPExamples/tree/master/RichText):
public sealed partial class MainPage
{
public static readonly FontFamily FONT_FAMILY = new FontFamily("Assets/paltn.ttf#Palatino-Roman");
public const int FONT_SIZE = 10;
private readonly Dictionary<string, object> FONT = new Dictionary<string, object>
{
{ AttrString.FONT_FAMILY_KEY, FONT_FAMILY },
{ AttrString.FONT_SIZE_KEY, FONT_SIZE },
{ AttrString.LINE_HEAD_INDENT_KEY, 10 },
{ AttrString.LINE_SPACING_KEY, 1.08 },
{ AttrString.FOREGROUND_COLOR_KEY, new SolidColorBrush(Colors.Black) }
};
// ReSharper disable once PrivateFieldCanBeConvertedToLocalVariable
private readonly RichTextBlock m_displayedText;
public MainPage()
{
InitializeComponent();
// create the text block:
m_displayedText = new RichTextBlock
{
MaxLines = 0, //Let it use as many lines as it wants
TextWrapping = TextWrapping.Wrap,
AllowFocusOnInteraction = false,
IsHitTestVisible = false,
Width = 80,
Height = 30,
Margin = new Thickness(100)
};
// set the content with the right properties:
AttrString content = new AttrString("Excerpt1 InkLink", FONT);
SetRichText(m_displayedText, content);
// add to the main panel:
MainPanel.Children.Add(m_displayedText);
// compute the text height: (this gives the wrong answer!!):
double textH = GetRichTextHeight(content, (float)m_displayedText.Width);
Console.WriteLine("text height: {0}", textH);
}
public static double GetRichTextHeight(AttrString text, float maxWidth)
{
if (text == null)
return 0;
CanvasDevice device = CanvasDevice.GetSharedDevice();
double finalH = 0;
foreach (AttributedToken textToken in text.Tokens)
{
CanvasTextFormat frmt = new CanvasTextFormat()
{
Direction = CanvasTextDirection.LeftToRightThenTopToBottom,
FontFamily = textToken.Get(AttrString.FONT_FAMILY_KEY, FONT_FAMILY).Source,
FontSize = textToken.Get(AttrString.FONT_SIZE_KEY, FONT_SIZE),
WordWrapping = CanvasWordWrapping.Wrap
};
CanvasTextLayout layout = new CanvasTextLayout(device, textToken.Text, frmt, maxWidth, 0f);
finalH += layout.LayoutBounds.Height;
}
return finalH;
//return textBlock.Blocks.Sum(block => block.LineHeight);
}
private static void SetRichText(RichTextBlock label, AttrString str)
{
if ((str == null) || (label == null))
return;
label.Blocks.Clear();
foreach (AttributedToken token in str.Tokens)
{
Paragraph paragraph = new Paragraph()
{
TextAlignment = token.Get(AttrString.TEXT_ALIGN_KEY, TextAlignment.Left),
TextIndent = token.Get(AttrString.LINE_HEAD_INDENT_KEY, 0),
};
double fontSize = token.Get(AttrString.FONT_SIZE_KEY, FONT_SIZE);
double lineSpacing = token.Get(AttrString.LINE_SPACING_KEY, 1.0);
paragraph.LineHeight = fontSize * lineSpacing;
paragraph.LineStackingStrategy = LineStackingStrategy.BlockLineHeight;
Run run = new Run
{
Text = token.Text,
FontFamily = token.Get(AttrString.FONT_FAMILY_KEY, FONT_FAMILY),
FontSize = fontSize,
Foreground = token.Get(AttrString.FOREGROUND_COLOR_KEY, new SolidColorBrush(Colors.Black)),
FontStyle = token.Get(AttrString.ITALIC_KEY, false) ?
Windows.UI.Text.FontStyle.Italic : Windows.UI.Text.FontStyle.Normal
};
paragraph.Inlines.Add(run);
label.Blocks.Add(paragraph);
}
}
}
public class AttrString
{
public const string FONT_FAMILY_KEY = "Fam";
public const string FONT_SIZE_KEY = "Size";
public const string LINE_HEAD_INDENT_KEY = "LhI";
public const string LINE_SPACING_KEY = "LSpace";
public const string FOREGROUND_COLOR_KEY = "Color";
public const string ITALIC_KEY = "Ita";
public const string TEXT_ALIGN_KEY = "Align";
public const string LINE_BREAK_MODE_KEY = "LineBreak";
public static Dictionary<string, object> DefaultCitationFont { get; set; }
public static Dictionary<string, object> DefaultFont { get; set; }
public List<AttributedToken> Tokens { get; set; }
public AttrString(string text, Dictionary<string, object> attributes)
{
Tokens = new List<AttributedToken>();
Append(text, attributes);
}
public AttrString(AttrString copy)
{
if (copy?.Tokens == null)
return;
Tokens = new List<AttributedToken>(copy.Tokens);
}
public AttrString Append(string text, Dictionary<string, object> attributes)
{
Tokens.Add(new AttributedToken(text, attributes));
return this;
}
public bool IsEmpty()
{
foreach (AttributedToken t in Tokens)
{
if (!string.IsNullOrEmpty(t.Text))
return false;
}
return true;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
foreach (AttributedToken t in Tokens)
{
sb.Append(t.Text);
}
return sb.ToString();
}
}
public class AttributedToken
{
public string Text { get; set; }
public Dictionary<string, object> Attributes { get; set; }
public AttributedToken(string text, Dictionary<string, object> attributes)
{
Text = text;
Attributes = attributes;
}
public T Get<T>(string key, T defaultValue)
{
if (string.IsNullOrEmpty(key) || (Attributes == null))
return defaultValue;
if (Attributes.ContainsKey(key))
return (T)Attributes[key];
else
return defaultValue;
}
public override string ToString()
{
return Text;
}
}
** 更新**:
进一步深入研究该问题后,该问题似乎与CanvasTextFormat 对象缺乏可配置性有关,尤其是第一行的缩进(在RichTextBlock 中使用属性Paragraph.TextIndent 表示)。有没有办法在CanvasTextFormat 对象中指定这样的设置?
【问题讨论】:
-
目前,
CanvasTextFormat没有类似的“TextIndent”属性。你能告诉我你的最终要求吗?为什么要使用win2D来获取字体高度? -
我想您可以将 RichTextBox 放在自定义面板中,在 MeasureOverride 期间,您可以在进行适当测量之前将其测量为面板宽度/无限高以获得高度。 CanvasTextLayout 比 CanvasTextFormat 更类似于 RichTextBlock,因为 Layout 可以使用单独的格式进行单独运行。
-
@XavierXie-MSFT 和 Johnny Westlake 感谢您的解释,我需要最快(性能方面)的方法来计算 RichTextBlock 中包含的文本的总高度,甚至在为 RichTextBlock 绘制之前第一次。我有一个包含数万个 RichTextBlocks 的场景,所以我还需要尽可能地保持层次结构。
-
@JohnnyWestlake 你是对的,确实我目前正在使用 CanvasTextLayout,在 GetRichTextHeight() 方法中传递一个 CanvasTextFormat 类型的参数,但我缺少的是告诉 CanvasTextLayout 第一行的方法我的 RichTextBlock 的缩进了 10。
-
@JohnnyWestlake 顺便说一句,如果一个完整的段落以相同的方式格式化,此方法有效,但在未来,我们可能会被要求在同一段落中使用不同的格式,这将需要增强GetRichTextHeight() 方法通过告诉 CanvasTextFormat 或 CanvasTextLayout 文本从指定位置开始(基本上,有一个缩进......)。您对如何解决这个问题有任何线索吗?
标签: c# uwp win2d richtextblock