How to reliably determine the width of a character in C#?

Viewed 514

I'm writing a C# program and I'm using a fixed-width font to display everything. Under this font, every Unicode character either occupies 1 character width or 2 character width. In the program, there is a feature that needs to determine a particular character occupies 1 character width or 2 character width. At first I use the regex [^\x00-\xFF] to solve the problem. If a character matches it, it occupies 1 character width, otherwise it's 2 character width. But later I found this is not correct. For example, these characters ┌─┬┐│├┼┤┴┘ don't fall in the range of [^\x00-\xFF] but they all just occupies 1 character width. I want to know in C# how to determine a specific character occupies 1 character width or 2 when using fixed-width font?

2 Answers

I'm also searching for the same question's answer... but I haven't found it. by the way, I finally write a library to get length of character (generate a range information which shows character length use Console.Write() and Console.CursorLeft, and then convert to C# code, when get character length, use binary search for higher speed)

nuget: NullLib.ConsoleEx Project: https://github.com/SlimeNull/NullLib.ConsoleEx

According to .NET documentation, if you know the font used1, you could use the GlyphTypeface API to get the "AdvanceWidths" of each glyph of your font.

You still have to map the character with glyph index in your font. You can use CharacterToGlyphMap to do that.

var character = 'x';

GlyphTypeface glyphTypeface = new GlyphTypeface(new Uri("file:///C:\\WINDOWS\\Fonts\\Kooten.ttf"));

var index = glyphTypeface.CharacterToGlyphMap[character];
var width = glyphTypeface.AdvanceWidths[index];

[1] To get current console's font details I would recommend to read following question: Get current console font info

Related question: How to find exact size for an arbitrary glyph in WPF?

Related