Tuesday, 25 August 2009

How to calculate the width/height of a string in a particular font

- Follow up from the listbox width issue -

This applies to mainly asp.net, but the technique for winforms isn't drastically different. What we need to use is a Graphics object to measure a string width. Here's how:


// Bitmap is solely required for creating the graphics object
Bitmap TextBitmap = new Bitmap(1, 1);
Graphics g = Graphics.FromImage(TextBitmap);

// Create the font relative to the text (let's say Arial 8)
Font myFont = new Font("Arial", 8);
SizeF fontSize = g.MeasureString("This is a test string", myFont);



Done. The values you need are fontSize.Height and fontSize.Width.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.