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 (eithe
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.