簡體   English   中英

如何在 c# winforms 中添加上標冪運算符

[英]How to add superscript power operators in c# winforms

我知道可以使用其 unicode 值將平方運算符添加到標簽中。( 如何在 .NET GUI 標簽中顯示上標字符? )。 有沒有辦法為標簽添加任何權力? 我的應用程序需要顯示多項式函數,即 x^7 + x^6 等。

謝謝,邁克

您可以使用(偉大的) 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屬性來更改大小和字體。

您還可以使用本機支持的UTF字符串的強大功能,並執行類似的擴展方法,將int(或甚至是uint)轉換為字符串,如:

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和諸如此類的事件處理程序),您甚至可以允許用戶編輯這樣的“上標兼容”字符串(通過從其他按鈕切換“上標模式”)在您的用戶界面上)。

你可以將unicode轉換為字符串,用於上標,下標和任何其他符號,並添加到字符串中。 例如:如果你想要10 ^ 6,你可以在C#或其他中編寫如下代碼。

電源6的unicode是U + 2076,電源7的unicode是U + 2077,所以你可以寫x ^ 6 + x ^ 7

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

我認為沒有確切正確的方法來做到這一點。 但是,您可以這樣做的一種方法是在此網站https://lingojam.com/SuperscriptGenerator 中輸入您想成為指數的數字。

然后復制轉換后的版本。 例如,我在那里放了一個 3,我得到的轉換版本是 ³。 然后你只需將它連接在一起。

現在您可以將其添加到標簽中...

mylabel.Text="m³";

或者無論如何你想要。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM