How to color individual characters and maintain proper spacing / kerning / alignment?

孤街浪徒 提交于 2020-01-21 15:28:40

问题


I want to use Graphics.DrawString to draw characters using individual colors.

The problem is that each time I call DrawString, I have to know where to position it (either using a Point or a Rectangle) relative to the other characters.

This is almost possible when taking into account the kerning and wrapping that happens when you use DrawString in a rectangle with a StringFormat. The StringFormat is important to specify alignment, wrapping, trimming, etc.

Ideally I'd be able to tell DrawString how to color each character individually. The other option is if I can measure a string in a rectangle using a StringFormat and then retrieve the X and Y positions of each character index, so that I can draw each one with its own brush.

I tried to measure each character individually, but that will not work because a combination of characters in a string is not the same width as each character measured on its own.

EDIT: Here is what is happening when I take a string, get the Region array, fill those regions with red and blue alternating, and then try to draw each individual character in those regions:

I am calling DrawString as follows:

g.DrawString(character, font, brush, region.GetBounds(g));

Also tried the following:

Rectangle bounds = Region.GetBounds(g);
g.DrawString(character, font, brush, new PointF(bounds.Left, bounds.Top));

And,

g.DrawString(character, font, brush, region.GetBounds(g), stringFormat);

Same results.


回答1:


GDI+'s DrawString is padding the result which explains the left offset you get.

Try to use the GDI to measure the string. Luckily this is implemented and easy to reach from .Net through the TextRenderer() object, f.ex:

Size sz = TextRenderer.MeasureText(character, 
                                   font, 
                                   new Point(Integer.MaxValue, Integer.MaxValue),
                                   TextFormatFlags.NoPadding);

You can also look into the TextRenderer.DrawText().

Of course, you can always modify your StringFormat instance to use center alignment and DrawString with a rectangle instead of point.

StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
Rectangle cr = new Rectangle(x, y, w, h); //same as the colored region
g.DrawString(character, font, brush, cr, sf);

Hope this helps.



来源:https://stackoverflow.com/questions/13163894/how-to-color-individual-characters-and-maintain-proper-spacing-kerning-align

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!