场景
我想在 WP7 上使用 Glyphs
创建一行对齐的文本,即触及周围矩形的左右边框。
我的解决方案
var glyphs = new Glyphs();
glyphs.FontUri = new Uri("/MyAssembly;component/MyPath/MyFont.ttf", UriKind.Relative);
glyphs.FontRenderingEmSize = 20;
glyphs.Fill = new SolidColorBrush(Colors.Red);
// measue width of space
glyphs.UnicodeString = " ";
glyphs.Measure(availableSize);
double spaceWidth = glyphs.DesiredSize.Width;
glyphs.InvalidateMeasure();
// setup justified text
string text = "Lorem Ipsum is dummy text of the printing and typesetting industry.";
int spaceCount = 10; // number of spaces in above text
glyphs.UnicodeString = text;
glyphs.Measure(availableSize); // now DesiredSize.Width = width of left aligned text
// I suspect my error to be in this formula:
double spaceAdvance = ((availableSize.Width - glyphs.DesiredSize.Width)
/ spaceCount + spaceWidth) / glyphs.FontRenderingEmSize * 100;
string spaceAdvanceString = String.Format(",{0};", spaceAdvance);
var indices = new StringBuilder();
foreach (char c in text)
{
if (c == ' ') indices.Append(spaceAdvanceString);
else indices.Append(';');
}
glyphs.Indices = indices.ToString();
问题与疑问
字形的右侧并没有完全接触到 availableSize.Width
-Border,而是偏离了一些像素,当有几行文本堆叠在一起时,这看起来很奇怪。
我的计算有什么问题吗?
最佳答案
这可能是浮点精度的问题。
一般而言,每个浮点算术运算都会在结果中引入至少等于机器精度(即,当与 1.0 相加时产生不同于 1.0 的浮点结果的最小数字)的误差。此错误称为舍入错误。舍入误差是累积的,有时取决于运算顺序。
代替
double spaceAdvance = ((availableSize.Width - glyphs.DesiredSize.Width)
/ spaceCount + spaceWidth) / glyphs.FontRenderingEmSize * 100;
尝试将乘法移到前面,即
double spaceAdvance = 100.0 * ((availableSize.Width - glyphs.DesiredSize.Width)
/ spaceCount + spaceWidth) / glyphs.FontRenderingEmSize;
或者,你也可以试试
double spaceAdvance = (100.0 * (availableSize.Width - glyphs.DesiredSize.Width)
/ spaceCount + 100.0 * spaceWidth) / glyphs.FontRenderingEmSize;
关于c# - Silverlight:字形宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5264537/