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

后端 未结 1 547
时光说笑
时光说笑 2021-01-22 18:46

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

相关标签:
1条回答
  • 2021-01-22 19:23

    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.

    0 讨论(0)
提交回复
热议问题