如何在C# WinForms中添加上标幂运算符?

5

我知道可以使用其unicode值将平方运算符添加到标签中(如何在.NET GUI标签中显示上标字符?)。是否有一种方法可以向标签添加任何幂次方呢?我的应用程序需要显示多项式函数,例如x^7 + x^6等。


您需要文本可编辑还是不可编辑? - digEmAll
@digEmAll 不需要改变。 - mikeythemissile
4个回答

9
你可以使用(很棒的)HtmlRenderer,并构建自己的支持HTML的标签控件。
以下是一个示例:
public class HtmlPoweredLabel : Control
{
    protected override void OnPaint(PaintEventArgs e)
    {
        string html = string.Format(System.Globalization.CultureInfo.InvariantCulture,
        "<div style=\"font-family:{0}; font-size:{1}pt;\">{2}</div>",
        this.Font.FontFamily.Name,
        this.Font.SizeInPoints,
        this.Text);

        var topLeftCorner = new System.Drawing.PointF(0, 0);
        var size = this.Size;

        HtmlRenderer.HtmlRender.Render(e.Graphics, html, topLeftCorner, size);

        base.OnPaint(e);
    }
}

使用示例:

// add an HtmlPoweredLabel to you form using designer or programmatically,
// then set the text in this way:
this.htmlPoweredLabel.Text = "y = x<sup>7</sup> + x<sup>6</sup>";

结果:

图片描述

请注意,此代码将您的html包装到一个div部分中,该部分将字体系列和大小设置为控件使用的字体系列和大小。因此,您可以通过更改标签的Font属性来更改大小和字体。

4
您可以使用原生支持的UTF字符串的强大功能,编写一个扩展方法,将整数(甚至是无符号整数)转换为字符串,示例如下:
public static class SomeClass {

    private static readonly string superscripts = @"⁰¹²³⁴⁵⁶⁷⁸⁹";
    public static string ToSuperscriptNumber(this int @this) {

        var sb = new StringBuilder();
        Stack<byte> digits = new Stack<byte>();

        do {
            var digit = (byte)(@this % 10);
            digits.Push(digit);
            @this /= 10;
        } while (@this != 0);

        while (digits.Count > 0) {
            var digit = digits.Pop();
            sb.Append(superscripts[digit]);
        }
        return sb.ToString();
    }

}

然后像这样使用那个扩展方法:

public class Etc {

   private Label someWinFormsLabel;

   public void Foo(int n, int m) {
     // we want to write the equation x + x^N + x^M = 0
     // where N and M are variables
     this.someWinFormsLabel.Text = string.Format(
       "x + x{0} + x{1} = 0",
       n.ToSuperscriptNumber(),
       m.ToSuperscriptNumber()
     );
   }

   // the result of calling Foo(34, 2798) would be the label becoming: x + x³⁴+ x²⁷⁹⁸ = 0

}

基于这个想法,并进行了一些小的额外调整(比如钩住文本框的TextChange等事件处理程序),您甚至可以允许用户编辑这样的“上标兼容”字符串(通过从用户界面上的其他按钮切换“上标模式”)。


0

我认为这并没有一个确切或适当的方法。但是你可以通过在这个网站https://lingojam.com/SuperscriptGenerator中输入你想要作为指数的数字来完成这个操作。

然后复制转换后的版本。例如,我在里面放了一个3,得到的转换版本是³。然后你只需要将它们连接在一起。

现在你只需要将其添加到标签中即可...

mylabel.Text="m³";

或者以任何你想要的方式。


0

您可以将Unicode转换为字符串,以获得上标、下标或其他符号,并将其添加到字符串中。

例如:如果您想要10^6,您可以在C#或其他语言中编写以下代码:

数字6的Unicode为U+2076,数字7的Unicode为U+2077,因此您可以将x^6+x^7写成:

label1.Text = "X" + (char)0X2076 + "X" + (char)0x2077;


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接