Reputation: 313
I have a System.Drawing.Font object. How I can check is that font is monospace?
I tried something like font.FontFamily == FontFamily.GenericMonospace
, but it's not properly working.
Upvotes: 4
Views: 3214
Reputation: 538
In C# WPF an easy but a little bit expensive method goes like that:
private static char[] charSizes = new char[] { 'i', 'a', 'Z', '%', '#', 'a', 'B', 'l', 'm', ',', '.' };
private bool IsMonospaced(FontFamily family)
{
foreach (Typeface typeface in family.GetTypefaces())
{
double firstWidth = 0d;
foreach (char ch in charSizes)
{
FormattedText formattedText = new FormattedText(
ch.ToString(),
CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
typeface,
10d,
Brushes.Black,
new NumberSubstitution(),
1);
if (ch == 'i') // first char in list
{
firstWidth = formattedText.Width;
}
else
{
if (formattedText.Width != firstWidth)
return false;
}
}
}
return true;
}
Upvotes: 1