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

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

    String.Length

    Returns the length of the string (number of characters).

    C#

    string MyString = "Stack Overflow String";
    Response.Write(MyString.Length);
    

    VB.net

    Dim MyString As String = "Stack Overflow String"
    Response.Write(MyString.Length);
    

    MSDN Reference

    http://msdn.microsoft.com/en-us/library/system.string.length.aspx

    Physical String Size Serverside

    I'm not sure why so many people are apparently determined to put forward the idea that it is 'flat out impossible' to do this server side, it isn't. You just need to be a little bit creative, and be willing to do a lot of testing.

    There is no native function I know of to measure the pixel dimensions of a string. You can achieve it in the following ways. Note you need to know:

    • The font family
    • Font size
    • Container dimensions (for when the text wraps lines)
    • Any other CSS rules such as word spacing are going to make the calculation a lot less accurate and more complex. Try and avoid it if accuracy is important.

    1. Render it to an image and measure image size

    Draw the text to a bitmap, and then measure it. This should be reasonably exact.

    2. Use a fixed width font

    If you are using a fixed width font and the text doesn't wrap, you can simply multiply its width by the number of characters.

    3. Rough estimation

    You could get a reasonably rough estimation on non fixed width fonts by picking some arbitrary character width number and multiplying it by total characters. Depends how accurate you want to be.

提交回复
热议问题