设置 MaxTextWidth 时出现 WPF 字对齐问题

2024-01-15

我正在使用 FormattedText 来显示文本。我需要根据提供的选项水平对齐文本。一切正常,直到我设置“MaxTextWidth”属性(我需要它来进行文字修剪)。如何在启用文字修剪的情况下对齐文本?

    FormattedText formatted_text = new FormattedText(
            text, System.Globalization.CultureInfo.GetCultureInfo("en-US"),
            FlowDirection.LeftToRight,
            typeface, em_size, brush);
   formatted_text.TextAlignment = TextAlignment.Right;
   drawingContext.DrawText(formatted_text, origin);

这可以很好地按预期对齐代码。但我需要修剪 MaxTextWidth 这个词。我在设置 MaxTextWidth 时遇到问题。如何计算MaxTextWidth?

图像中的点就是原点。

这是我不设置最大文本宽度时得到的结果

当我设置 MaxTextWidth = 100 时

如何计算 MaxTextWidth 以便对齐修剪后的句子?

Edit: Adding more screenshots Before setting MaxTextWidth, properly aligned

在设置MaxTextWidth之前,正确对齐, 设置后

enter image description here I lose the word alignment, look w.r.t the reference point shown


这是一种奇怪的行为DrawingContext.DrawText https://msdn.microsoft.com/en-us/library/system.windows.media.drawingcontext.drawtext.aspx that MaxTextWidth https://msdn.microsoft.com/en-us/library/system.windows.media.formattedtext.maxtextwidth.aspx有影响origin. If FormattedText是右对齐的并且MaxTextWidth = 0,即默认值,DrawText把 文本位于原点左侧。如果MaxTextWidth > 0, DrawText将文本置于原点右侧。

Hence you have to substract MaxTextWidth from origin.X if right aligned and the half if centered. Here is an example. Blue dots are the desired origins and red ones the corrected. DrawText origin example

using System.Windows;
using System.Windows.Media;

public void DrawTextTest(DrawingContext dc) {
    var y = 100.0;
    foreach (var align in new TextAlignment[]{
        TextAlignment.Left, TextAlignment.Center, TextAlignment.Right}) {
        foreach (var width in new double[] { 0.0, 150.0 }) {
            DrawText(dc, new Point(400, y), align, width);
            y += 25.0;
        }
        y += 45.0;
    }
}

private void DrawText(DrawingContext dc, Point origin,
    TextAlignment align, double maxTextWidth) {
    var f = new FormattedText(
        "This is a text with TextAlignment = " + align.ToString()
            + " and MaxTextWidth = " + maxTextWidth.ToString() + ".",
        System.Globalization.CultureInfo.CurrentCulture,
        FlowDirection.LeftToRight,
        new Typeface("Arial"), 12.0, Brushes.Black
    ) {
        TextAlignment = align,
        MaxTextWidth = maxTextWidth
    };

    dc.DrawEllipse(Brushes.Blue, null, origin, 1.0, 1.0);
    var correctionX = -maxTextWidth * (align == TextAlignment.Right ? 1.0
        : (align == TextAlignment.Center ? 0.5 : 0.0));
    origin.Offset(correctionX, 0.0);
    dc.DrawEllipse(Brushes.Red, null, origin, 1.0, 1.0);
    dc.DrawText(f, origin);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

设置 MaxTextWidth 时出现 WPF 字对齐问题 的相关文章

随机推荐