How to determine the size of a string given a font

后端 未结 3 1098
再見小時候
再見小時候 2020-12-03 10:48

I have a small form that displays some progress information.
Very rarely I have to show a rather long message and I want to be able to resize this form when needed so th

相关标签:
3条回答
  • 2020-12-03 11:25

    It depends on the rendering engine being used. You can basically switch between GDI and GDI+. Switching can be done by setting the UseCompatibleTextRendering property accordingly

    When using GDI+ you should use MeasureString:

    string s = "A sample string";
    
    SizeF size = e.Graphics.MeasureString(s, new Font("Arial", 24));
    

    When using GDI (i.e. the native Win32 rendering) you should use the TextRenderer class:

    SizeF size = TextRenderer.MeasureText(s, new Font("Arial", 24));
    

    See this article: Text Rendering: Build World-Ready Apps Using Complex Scripts In Windows Forms Controls

    0 讨论(0)
  • 2020-12-03 11:30

    Back in the Win32 I was using the equivalent for VisualStyleRenderer::GetTextExtent function for this.

    0 讨论(0)
  • 2020-12-03 11:31

    How about this:

    Size stringsize = graphics.MeasureString("hello", myFont);
    

    (Here is the MSDN link.)

    0 讨论(0)
提交回复
热议问题