(C#, Microsoft .NET Framework 3.5)
Hello!
I'm in the process of creating a custom text control and I want to add functionality for superscripts and subscripts. I'm using TextRenderer for drawing and measuring text because Graphics.DrawString and Graphics.MeasureString does not come with a "NoPadding" option.
When drawing superscripts and subscripts, I'll specify the x-position as the width of the normal text. This works fine for regular and bold text, however, a problem arises when drawing italic text. Italic letters overlap eachother and so the width of an italic character returned by TextRenderer.MeasureText is shorter than what is actually drawn. So when drawing superscripts, the beginning of the superscript text crashes into the ending part of the normal text.
I can illustrate this with the following code:
private void Form1_Paint(object sender, PaintEventArgs e)
{
// The font we'll be using
Font font = new Font("Times New Roman", 200, FontStyle.Italic);
// The string we'll be measuring
string s = "d";
// Measure the text
Size size = TextRenderer.MeasureText(e.Graphics, s, font, new Size(int.MaxValue, int.MaxValue), TextFormatFlags.NoPadding);
// Draw the text at x- and y-coordinates 0 and 0, respectively.
TextRenderer.DrawText(e.Graphics, "d", font, new Point(0, 0), Color.Blue, TextFormatFlags.NoPadding);
// Now the x-coordinate at the end of the text should be size.Width
// Draw a vertical line at the end of the text, with length 1000
e.Graphics.DrawLine(Pens.Red, new Point(size.Width, 0), new Point(size.Width, 1000));
// Notice that the red line goes straight through the d-character which will cause a problem
// when adding superscripts (if I was to place the superscript x-coordinate at size.Width)
}
I'm looking for some value to compensate for this. Have I overlooked a function in the .NET Framework? Is there some API function?
Thanks in advance!
Any help is appreciated!
Sincerely yours, Emil