How to set multiple FontStyles when instantiating a font?

In looking at the constructors for the System.Drawing.Font class there is a parameter to pass in one of the FontStyles defined in the System.Drawing.FontStyle enum.

ie.
Bold
Italic
Regular
Underline

and there are boolean properties for Bold, Italic, Underline etc. in the instantiated object, but they are read only.

What if I want to define my font to have multiple styles like Bold and Underline?

How can I do this?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

The FontStyle enum is a Flags enum. This means that its members are all powers of two, allowing you to combine them using a binary OR.

For example, if you want bold and underline, you’d pass

FontStyle.Bold | FontStyle.Underline

The vertical bar (|) is the binary OR operator.

Method 2

In the Font constructor, you can combine multiple FontStyles using the OR operator:

Font font = new Font(this.Font, FontStyle.Bold | FontStyle.Underline);

Method 3

You could use something like this, in order to avoid multiple ifs for each case:

//define a font to use.
Font font;

font = new Font(fontname, fontsize, GraphicsUnit.Pixel);

if (bold)
    font = new Font(font, font.Style ^ FontStyle.Bold);
if (italic)
    font = new Font(font, font.Style ^ FontStyle.Italic);
if (underline)
    font = new Font(font, font.Style ^ FontStyle.Underline);
if (strikeout)
    font = new Font(font, font.Style ^ FontStyle.Strikeout);


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x