Programmer's Weblog

All possible FontStyles

Thursday, January 3, 2008

That was funny. To instantiate Font in .NET 2.0 you call one of many Font's constructors. Basically you provide a font family (either an object of the class FontFamily or a name of one as a string), size and FontStyle. There is a constructor that doesn't take a FontStyle, it assumes the FontStyle.Regular as default.

A FontFamily is a collection of fonts. Arial family will have Arial Regular, Arial Bold, Arial Bold Italic...

Now, in theory there might be a family with only Bold Italic. The requirement is in case there is no style the user requested, give back a font from the family in any available style.

Unfortunatelly in FontFamily object there is no property returning available members of the family, but there is a method for checking if given FontStyle is available.

FontStyle is an enumeration with the following members.

FontStyle.Regular = 0
FontStyle.Bold = 1
FontStyle.Italic = 2
FontStyle.Underline = 4
FontStyle.Strikeout = 8

A font style can be created by bitwise or-ing the values. For example Bold Italic can be defined by FontStyle.Bold | FontStyle.Italic wihich makes 3.

How to generate all possible combinations?

for i in xrange(16):
    fontStyle = Enum.ToObject(FontStyle, i)
    if fontFamily.IsStyleAvailable(fontStyle):
        return Font(fontFamily, fontSize, fontStyle)

Integers from 0 to 15 form all valid combinations of the FontStyle. This sixteen numbers can be represented with 4 bits, 15's binary representation having them all lit (8 + 4 + 2 + 1).

Labels: ,

0 comments

Comments

leave feedback