场景
我想在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
-边界没有完全接触,而是有一些像素偏离,当有多行文本堆叠在一起时,这看起来很奇怪。
我的计算有什么问题吗?
(spaceCount * spaceWidth) + <widthOf>(text.Replace(" ", "") == <widthOf>(text)
吗? 我所知道的少量排版技巧是,您可以应用各种技巧使其看起来均匀,并在可能的情况下对其进行像素对齐。 - Albin Sunnanbo