|
|||||||||||||||||||||||
|
|||||||||||||||||||||||
|
Announcements
Chapters
Services
Feature Zones
|
Introduction
The differences between what is computed and what is really drawn on the screen are related to how GDI+ computes its widths when using hinting and antialiasing. Here are the gory details. A known work-around is to make GDI+ display its string antialiased, in which case the measured width matches the displayed result. If you want to draw standard strings (to match the GUI appearance, for instance), you are left out. First, naive solutionThe code I present here can be inserted into any class which needs to compute the real width of a string (shown by the yellow background above). The trick I use to compute the real string width is to ask GDI+ to draw the string into a bitmap and then find the position of the last character by reading back the pixels. A few optimisations ensure that this gets done as fast as possible (small bitmap, few pixels). static public int MeasureDisplayStringWidth(Graphics graphics, string text,
Font font)
{
const int width = 32;
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap (width, 1,
That's all, folks. Right-to-left scripts won't probably work with this piece of code. Another solution...It is also possible to get the accurate string geometry by using static public int MeasureDisplayStringWidth(Graphics graphics, string text,
Font font)
{
System.Drawing.StringFormat format = new System.Drawing.StringFormat ();
System.Drawing.RectangleF rect = new System.Drawing.RectangleF(0, 0,
1000, 1000);
System.Drawing.CharacterRange[] ranges =
Post ScriptBoth functions only work with non-empty strings. The second solution will strip the trailing spaces; the first solution will take them in account. Choose the one which best fits your needs
|
||||||||||||||||||||||