如何给单个字符着色并保持适当的间距/字距/对齐方式? [英] How to color individual characters and maintain proper spacing / kerning / alignment?
问题描述
我想使用Graphics.DrawString使用单独的颜色绘制字符.
I want to use Graphics.DrawString to draw characters using individual colors.
问题在于,每次调用DrawString时,我都必须知道相对于其他字符将其放置在何处(使用Point或Rectangle).
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.
考虑到在带StringFormat的矩形中使用DrawString时发生的字距调整和换行,这几乎是可能的. StringFormat对于指定对齐方式,换行,修剪等非常重要.
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.
理想情况下,我可以告诉DrawString如何分别为每个字符着色.另一个选择是,如果我可以使用StringFormat测量矩形中的字符串,然后检索每个字符索引的X和Y位置,以便可以使用自己的画笔绘制每个.
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.
编辑: 这是当我取一个字符串,获取Region数组,用红色和蓝色交替填充这些区域,然后尝试在这些区域中绘制每个字符时发生的事情:
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:
我正在按如下方式调用DrawString:
I am calling DrawString as follows:
g.DrawString(character, font, brush, region.GetBounds(g));
还尝试了以下操作:
Rectangle bounds = Region.GetBounds(g);
g.DrawString(character, font, brush, new PointF(bounds.Left, bounds.Top));
然后
g.DrawString(character, font, brush, region.GetBounds(g), stringFormat);
相同的结果.
推荐答案
GDI +的DrawString对结果进行填充,解释了得到的左偏移量.
GDI+'s DrawString is padding the result which explains the left offset you get.
尝试使用GDI来测量字符串.幸运的是,这已经实现,并且可以通过TextRenderer()
对象f.ex从.Net轻松访问:
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);
您还可以查看TextRenderer.DrawText()
.
当然,您始终可以修改StringFormat
实例以使用中心对齐和DrawString
并使用矩形而不是点.
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);
希望这会有所帮助.
这篇关于如何给单个字符着色并保持适当的间距/字距/对齐方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!