How to programmatically measure string pixel width in ASP.NET?

前端 未结 8 1452
忘了有多久
忘了有多久 2020-12-19 03:06

How do you get the size of a string? In Windows Forms it\'s easy, I just use graphics object and then MeasureString function. In ASP.NET I\'m not sure how to do this.

8条回答
  •  轮回少年
    2020-12-19 03:44

    Like Tom Gullen is saying. You can just create a bitmap and messure the string. I have this code I use to find the width/length in pixel. Just change the font and size.

    // Bitmap class namespace:
    using System.Drawing;
    
    ...
    
    private float GetWidthOfString(string str)
    {
        Bitmap objBitmap = default(Bitmap);
        Graphics objGraphics = default(Graphics);
    
        objBitmap = new Bitmap(500, 200);
        objGraphics = Graphics.FromImage(objBitmap);
    
        SizeF stringSize = objGraphics.MeasureString(str, new Font("Arial", 12));
    
        objBitmap.Dispose();
        objGraphics.Dispose();
        return stringSize.Width;
    }
    

    Just wanted to show an example.

提交回复
热议问题