Font Class
System.Drawing
Introduction
The Font
class represents a font, which is a collection of characters with a specific design. It allows you to specify the typeface, style, and size of text when rendering it using the System.Drawing namespace, particularly with the Graphics
class.
Syntax
public sealed class
Font
: ICloneable, IDisposable
Constructors
Several constructors are available to create a Font
object:
Font(string familyName, float emSize)
Initializes a new instance of the Font
class with the specified system font family name and size.
var myFont = new Font("Arial", 12.0f);
Font(string familyName, float emSize, FontStyle style)
Initializes a new instance of the Font
class with the specified system font family name, size, and style.
var boldFont = new Font("Times New Roman", 14.0f, FontStyle.Bold);
Font(string familyName, float emSize, GraphicsUnit unit)
Initializes a new instance of the Font
class with the specified system font family name, size, and unit of measure.
Font(FontFamily family, float emSize)
Initializes a new instance of the Font
class with the specified System.Drawing.FontFamily
and size.
Properties
Name | Description |
---|---|
Name |
Gets the name of this font. |
Size |
Gets the point size of this font. |
Style |
Gets the style attributes of this font. |
famÃlias |
Gets the System.Drawing.FontFamily associated with this font. |
Unit |
Gets the unit of measure for this font. |
Methods
Dispose()
Releases all resources used by this Font
object.
// In a using statement or explicit dispose call
using (Font myFont = new Font("Verdana", 10.0f))
{
// Use the font here
}
// Font is automatically disposed here
Clone()
Creates an object that is a copy of the current instance.
Example Usage
This example demonstrates how to create a font and use it to draw text on a form.
// Assume 'g' is an instance of System.Drawing.Graphics
using
System.Drawing;
public void DrawTextWithFont(Graphics g)
{
using (Font titleFont = new Font("Segoe UI", 16.0f, FontStyle.Bold))
{
g.DrawString("Document Title", titleFont, Brushes.Black, new PointF(50, 50));
}
using (Font bodyFont = new Font("Arial", 10.0f, FontStyle.Regular, GraphicsUnit.Point))
{
string paragraph = "This is the main content of the document. Using different fonts can improve readability and visual appeal.";
g.DrawString(paragraph, bodyFont, Brushes.DarkGray, new RectangleF(50, 100, 400, 150));
}
}