Determine how wide a rendered character is in .NET

后端 未结 7 1430
Happy的楠姐
Happy的楠姐 2021-01-02 01:03

Lets say I render the character \"A\" to the screen with a size 14 font in Arial Regular. Is there a way in C# to calculate how many pixels wide it is?


The wa

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-02 01:49

    It depends on the rendering engine being used. .NET may use GDI or GDI+. Switching can be done by setting the UseCompatibleTextRendering property accordingly or calling the Application.SetCompatibleTextRenderingDefault method.

    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));
    

    More details are described in this article:

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

    Note that the above talks about Windows Forms. In WPF you would be using FormattedText

提交回复
热议问题