c# - Silverlight:字形宽度

标签 c# .net silverlight windows-phone-7

场景

我想在 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/

相关文章:

.net - .NET 中具有通用+特定属性的 SOA 消息格式的最佳实践

c# - 对于 Silverlight 4 Visual Studio 解决方案,版本控制需要什么?

c# - 我下载了 VS 2019 企业版。当我尝试编译 .net core 3.0 项目时,我遇到了一个问题

带小数位的 C# 计算

c# - Nunit 未在测试项目类库 (VS2012) 中遇到断点

.net - 日志记录框架和多线程兼容性

c# - 微调器图形在 jQuery UI 对话框中未正确显示

c# - Entity Framework + ASP.NET Identity + Repository Pattern - 如何在加载用户的同时加载角色

c++ - 在 C++ 中托管 Silverlight

c# - 为什么 TextBlock 可以显示代码隐藏属性值,但 border/padding 却无法使用它?