Measuring Text and Fonts

Posted: May 16th, 2004 | No Comments »

I could not remember how to measure the length of a text according to its fonts (a classic in GUI programming). So here we go:

in Java: (JFC in a Nutshell)

// get the FontRenderContext from the Graphics object
FontRenderContext frc = g.getFontRenderContext();
// get the bounds and metrics according to the message String
Rectangle2D bounds = f.getStringBounds(message, frc);
LineMetrics metrics = f.getLineMetrics(message, frc);
// The width of our text
float width = (float) bounds.getWidth();
// Total line height
float lineheight = metrics.getHeight();
// Top of text to baseline
float ascent = metrics.getAscent();

in C#: (.NET Compact Framework FAQ)

//use the Graphics from the PaintEventArgs e
SizeF sSize = e.Graphics.MeasureString(s, font);
Rectangle r = new Rectangle(9, 199,(int)sSize.Width + 1, (int)sSize.Height + 1);
e.Graphics.DrawRectangle(pen, r);
e.Graphics.DrawString(s, font, brush, 10.0f, 200.0f);


Comments are closed.