【问题标题】:Render superscript in WPF在 WPF 中渲染上标
【发布时间】:2019-09-22 20:40:48
【问题描述】:

代码如下:

static readonly char[] s_expChar = "eE".ToCharArray();

static void setValue( TextBlock target, double val )
{
    string text = val.ToString();
    int indE = text.IndexOfAny( s_expChar );
    if( indE > 0 )
    {
        string normal = text.Substring( 0, indE ) + "·10";

        string ss = text.Substring( indE + 1 );
        if( ss.StartsWith( "0" ) )
            ss = ss.Substring( 1 );
        else if( ss.StartsWith( "-0" ) )
            ss = "-" + ss.Substring( 2 );

        target.Inlines.Clear();
        target.Inlines.Add( new Run( normal ) );
        Run rSuper = new Run( ss );
        Typography.SetVariants( rSuper, FontVariants.Superscript );
        target.Inlines.Add( rSuper );
    }
    else
    {
        target.Text = text;
    }
}

这是输出:

如您所见,- 字符的垂直对齐被破坏,似乎不受FontVariants.Superscript 的影响。如何解决?

在实时可视化树的调试器中,我看到 2 次运行具有正确的值,即第二次运行文本 -6,包括 -

【问题讨论】:

标签: c# wpf windows .net-4.7


【解决方案1】:

Typography.Variants 应该与正确的字体和正确的字符一起使用。因此,例如这段 XAML 可能无法正常工作:

<TextBlock FontSize="20">
    <TextBlock.Inlines>
        <Run Text="2e" />
        <Run Typography.Variants="Superscript" Text="-3" />
    </TextBlock.Inlines>
</TextBlock>

如您所见,“-”符号未按预期对齐。事实上,Typography.Variants 仅适用于 OpenType font(我建议您使用 Palatino LinotypeSegoe UI)。此外,将减号与Superscript 排版变体一起使用是不正确的:正确的字符称为superscript minus&amp;#8315; 是它的十进制表示)。

所以正确的 XAML 将是:

<TextBlock FontSize="20" FontFamily="Segoe UI">
    <TextBlock.Inlines>
        <Run Text="2e" />
        <Run Typography.Variants="Superscript" Text="&#8315;3" />
    </TextBlock.Inlines>
</TextBlock>

它将按预期显示。希望对你有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-30
    • 2010-10-19
    • 2011-05-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多