问题描述
我想在我的游戏中绘制以下字符串
I want to draw following string in my game
相比之下,宇宙中有 10^75 个粒子.
其中 10 以标准化的科学记数法进行格式化(就像我们在学校时所做的那样).
where 10 is formatted in a normalized scientific notation (as we've been doing in school).
我使用 SpriteBatch.DrawString 方法,但我无法找到一个完整的解决方案.有一些琐碎的:
I use SpriteBatch.DrawString method, but I cannot figure out a nite solution. There are a few trivial ones:
- 绘制两个字符串,其中第二个字符串的字体较小或被缩放.
- 绘制图像.
我一直在研究 UTF 表,但似乎不可能.
I've been looking at UTF tables, but seems it's not possible.
我是否必须为此任务使用特殊字体?
Do I have to have special font for this task?
推荐答案
我不熟悉 XNA,但在 Silverlight 项目中,我不得不做同样的事情,我最终从上标字符构造了科学记数法数字.
I'm not familiar with XNA but in a Silverlight project where I had to do the same thing I ended up constructing scientific notation numbers from superscript characters.
>
您不需要特殊字体,只需要具有下面使用的上标字符的 Unicode 字体即可.
You don't need a special font, just a Unicode font which has the superscript characters used below.
这是将数字 0-9 映射到适当字符的代码:
Heres the code to map digits 0-9 to the appropriate character:
private static string GetSuperscript(int digit)
{
switch (digit)
{
case 0:
return "\x2070";
case 1:
return "\x00B9";
case 2:
return "\x00B2";
case 3:
return "\x00B3";
case 4:
return "\x2074";
case 5:
return "\x2075";
case 6:
return "\x2076";
case 7:
return "\x2077";
case 8:
return "\x2078";
case 9:
return "\x2079";
default:
return string.Empty;
}
}
这会将您的原始双精度数转换为科学记数法
And this converts your original double into scientific notation
public static string FormatAsPowerOfTen(double? value, int decimals)
{
if(!value.HasValue)
{
return string.Empty;
}
var exp = (int)Math.Log10(value.Value);
var fmt = string.Format("{{0:F{0}}}x10{{1}}", decimals);
return string.Format(fmt, value / Math.Pow(10, exp), FormatExponentWithSuperscript(exp));
}
private static string FormatExponentWithSuperscript(int exp)
{
var sb = new StringBuilder();
bool isNegative = false;
if(exp < 0)
{
isNegative = true;
exp = -exp;
}
while (exp != 0)
{
sb.Insert(0, GetSuperscript(exp%10));
exp = exp/10;
}
if(isNegative)
{
sb.Insert(0, "-");
}
return sb.ToString();
}
所以现在你应该可以使用 FormatAsPowerOfTen(123400, 2)
得到 1.23x10⁵
.
So now you should be able to use FormatAsPowerOfTen(123400, 2)
resulting in 1.23x10⁵
.
这篇关于用标准化的科学记数法绘制字符串(上标)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!