Measuring a string drawn with a specific font

Measuring a string drawn with a specific font

When you’re dynamically drawing text (either on a Windows Form or Web Form application), you may need to calculate the width and height of a string printed with a particular font. This is easy with the Graphics class’s Measure string method, that takes in input the string being measured, and the font it will be printed with. Follows an example:

' create a new bitmapDim bmp As New Bitmap(400, 200, Drawing.Imaging.PixelFormat.Format16bppRgb565)' get the underlying Graphics objectDim gr As Graphics = Graphics.FromImage(bmp)' measure the stringDim stringSize As SizeF = gr.MeasureString("Test string", _    New Font("Courier New", 18, FontStyle.Bold, GraphicsUnit.Pixel))

Finally you can read the Height and Width properties of the returned SizeF variable (stringSize) in the example above.

See also  10 Best Apps to Help You Read More Books in Less Time

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist