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

前端 未结 8 1463
忘了有多久
忘了有多久 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:40

    The following method will provide the size of a String rendered in a given font:

    private RectangleF sizeOfString(string text, Font font)
    {
        GraphicsPath path = new GraphicsPath();
        path.AddString(text, font.FontFamily, (int)font.Style, font.Size, new Point(0, 0), new StringFormat());
        return path.GetBounds();
    }
    

    You could then use this to get the width as follows

    float width = sizeOfString("Hello World", someFont).Width;
    

提交回复
热议问题