I have a problem with C # GDI + draw string functions - I cannot get the exact size of my drawn string - without an internal lead and an external one, only em em. The font / line APIs provided by Microsoft seem to always draw a bounding box that is a few pixels larger than the text, even after I removed the inner master.
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
g.Clear(Color.Black);
String text = "The quick brown fox jumps over the lazy dog";
Font font = new System.Drawing.Font(FontFamily.GenericSerif, 24);
float internalLeading = font.Size * (font.FontFamily.GetCellAscent(font.Style) + font.FontFamily.GetCellDescent(font.Style) - font.FontFamily.GetEmHeight(font.Style)) / font.FontFamily.GetEmHeight(font.Style);
StringFormat format = StringFormat.GenericTypographic;
format.Trimming = StringTrimming.None;
format.FormatFlags = StringFormatFlags.NoWrap;
System.Drawing.RectangleF rect = new System.Drawing.RectangleF(0, 0, pictureBox1.Width,pictureBox1.Height);
System.Drawing.CharacterRange[] ranges = { new System.Drawing.CharacterRange(0, text.Length) };
System.Drawing.Region[] boundings = new System.Drawing.Region[1];
format.SetMeasurableCharacterRanges(ranges);
boundings = g.MeasureCharacterRanges(text, font, rect, format);
rect = boundings[0].GetBounds(g);
g.DrawString(text, font, new SolidBrush(Color.Red), new RectangleF(0,0,rect.Width,rect.Height), format);
g.DrawRectangle(Pens.Yellow, rect.X, rect.Y + internalLeading, rect.Width, rect.Height - internalLeading);
}
And the result is shown below. We can see that a few pixels remain between the text and the top edge of the bounding box.

I can get the exact size of the drawn line by reading the pixels in the image and calculating the bounding box myself. But it is slow. Can I find out if there is an easy way to just get around this?
ncite source
share