Determine how wide a rendered character is in .NET

后端 未结 7 1369
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 02:04

    Not really, you can only make an estimate. TrueType hinting, kerning and glyph overhang makes measuring individual characters next to impossible. Some code:

        public float GetAWidth() {
            using (var font = new Font("Arial", 14)) {
                SizeF size = TextRenderer.MeasureText(new string('A', 100), font);
                return size.Width / 100;
            }
        }
    

    That returns 13.1 on my machine. Avoid doing this.

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