开发者

How to get a string width

开发者 https://www.devze.com 2023-04-11 19:21 出处:网络
I need开发者_JAVA技巧 to build a function in a class library that take a string and a specific font for this string then get the width of the string

I need开发者_JAVA技巧 to build a function in a class library that take a string and a specific font for this string then get the width of the string

So how could I get the string boundary width ?


Another way to do this is with a TextRenderer, and call its MeasureString method, passing the string and the font type.

MSDN Example:

private void MeasureText1(PaintEventArgs e)
{
    String text1 = "Measure this text";
    Font arialBold = new Font("Arial", 12.0F);
    Size textSize = TextRenderer.MeasureText(text1, arialBold);
    TextRenderer.DrawText(e.Graphics, text1, arialBold, 
        new Rectangle(new Point(10, 10), textSize), Color.Red);  
}

NOTE: This is just an alternate solution to the (equally valid) one already posted by @Neil Barnwell (in case you already have a reference to System.Windows.Forms in your project, this might be more convenient).


You can get a Graphics object (using Control.CreateGraphics() on the container you intend the text for) and call MeasureString() to do this. It's a fairly common GDI+ technique.

More information from MSDN: http://msdn.microsoft.com/en-us/library/6xe5hazb.aspx


You can use this:

private float getTextSize(string text)
    {
        Font font = new Font("Courier New", 10.0F);
        Image fakeImage = new Bitmap(1, 1);
        Graphics graphics = Graphics.FromImage(fakeImage);
        SizeF size = graphics.MeasureString(text, font);
        return size.Width;
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号