![]() |
Multimedia »
GDI+ »
General
Intermediate
Measuring stringsBy Alberto VendittiAn example of using the Graphics.MeasureString() method. |
VB, Windows, .NET 1.0, .NET 1.1, GDI+, VS.NET2003, Dev
|
|
Advanced Search |
|
|
|
||||||||||||||||
Suppose you have a list of companies in a database table. Someone asked you to print each company name on a different label, using a specified font and font size. You have to be sure that all the company names will fit into the labels, without any word-wrap; you can introduce abbreviations if a company name doesn't fit.
The font you are using is not a fixed-length font but a proportional font, so the character length of each string cannot be used to anticipate the real printed length of the string. How can you do?
You simply have to "measure" each string, computing which width it will have when printed in the specified font and with the specified font size. To do this, you can use the MeasureString() method of the .NET Framework Graphics class.
The simple application I wrote helps you in "measuring" strings, given a font and a font size. The core measuring functionality is in the Measure() subroutine:
Private Sub Measure(ByVal BannerText As String, _
ByVal FontName As String, ByVal FontSize As Single, _
ByRef Width As Single, ByRef Height As Single)
Dim b As Bitmap
Dim g As Graphics
Dim f As New Font(FontName, FontSize)
' Compute the string dimensions in the given font
b = New Bitmap(1, 1, PixelFormat.Format32bppArgb)
g = Graphics.FromImage(b)
Dim stringSize As SizeF = g.MeasureString(BannerText, f)
Width = stringSize.Width
Height = stringSize.Height
g.Dispose()
b.Dispose()
End Sub
How to use the application:

Of course, this application is only an example. In a real situation, you will have to integrate a subroutine like Measure() inside a program that will: fetch your data from the database table; measure the string; warn you about "too long" strings and let you modify them, storing them again in the data source.
| You must Sign In to use this message board. | ||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||
General
News
Question
Answer
Joke
Rant
Admin
|
PermaLink |
Privacy |
Terms of Use
Last Updated: 29 Sep 2004 Editor: Smitha Vijayan |
Copyright 2004 by Alberto Venditti Everything else Copyright © CodeProject, 1999-2009 Web17 | Advertise on the Code Project |