Programmatically measuring text length using GDI+ Graphics.MeasureString issue
I have the following code that is working on my local machine (Win 7, .NET 4), but it doesn't seem to work on the server. I want to programmatically measuring text length
Could anyone please help with it?
private float GetTextSize(string text, float textSize)
{
using (Bitmap bmp = new Bitmap(1, 1))
{
bmp.SetResolution(96, 96);
using (Graphics g = Graphics.FromImage(bmp))
{
using (System.开发者_开发问答Drawing.Font font = new System.Drawing.Font(fontName, textSize))
{
return g.MeasureString(text, font).Width;
}
}
}
}
I will consider any better solution if available.
Update:
How to detect if a font type is available on the machine?
Update 2:
Why does my question get minus points? Could anyone please give it an up vote.
Thanks in advance!
The problem is that it will return different text length even for text that has the same number characters, e.g. 1234 is longer than abcd for some font type. My previous logic is to compare the number of characters for each text, and pass the longest text to the method, which is not correct based on that reason.
The solution is to call the method for each text, and text length returned from the method is reliable to compare.
精彩评论