2013-02-23 75 views
4

我知道使用unicode值可以将square运算符添加到标签中(How can I show a superscript character in .NET GUI labels?)。有没有办法给标签添加任何电源?我的应用程序需要显示多项式函数,即,x^7个+ X^6个如何在c#winforms中添加上标电源运算符

谢谢, 迈克

+0

您是否需要将文本编辑或不编辑? – digEmAll 2013-02-23 16:17:52

+0

@digEmAll不,不需要更改 – mikeythemissile 2013-02-23 16:22:16

+0

好吧,那么你可以检查我的答案中的解决方案是否符合你的需求;) – digEmAll 2013-02-23 16:30:51

回答

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>"; 

结果:

enter image description here

注意,这个代码封装您的HTML到一个div节设置字体系列和大小到控件使用的字体。因此,您可以通过更改标签的Font属性来更改大小和字体。

+0

谢谢,这真的很酷! – mikeythemissile 2013-02-23 16:37:03

3

你也可以使用原生支持UTF串的力量,这样做并扩展方法转换整数(甚至的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和诸如此类的事件处理程序),你甚至可以允许用户编辑这样的“标补偿可用“字符串(通过在用户界面上的其他按钮上打开和关闭”上标模式“)。

+0

感谢上标文本列表。复制粘贴为我工作! – trailmax 2013-07-17 11:13:41

0

您可以将unicode转换为上标,下标和任何其他符号的字符串并添加到字符串中。 例如:如果你想要10^6,你可以在C#或其他代码中编写代码如下:

unicode for power 6 is U + 2076 and power 7 is U + 2077,所以你可以写x^6 + x^7 as

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