StringFormat Class

The StringFormat class defines how text is formatted when it is drawn on a screen or on a printer. It provides a comprehensive set of properties that control text alignment, wrapping, clipping, hot tracking, and measurement.

Overview

When you draw text using the GDI+ Graphics object, you can optionally provide a StringFormat object to customize the appearance and layout of the text. This allows for precise control over how text is rendered, including:

Syntax

public sealed class StringFormat : ICloneable

Constructors

Properties

Methods

Enumerations

The StringFormat class uses several enumerations to define its behavior:

Example Usage

The following example demonstrates how to create a StringFormat object and use it to draw text with specific alignment and trimming.

using System.Drawing;

// Create a Graphics object (assume it's already created and configured)
Graphics graphics = /* ... get your Graphics object ... */;

// Create a StringFormat object for right alignment and word trimming
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Far;
sf.Trimming = StringTrimming.Word;
sf.FormatFlags = StringFormatFlags.DirectionRightToLeft; // Example of another flag

// Define the text and the rectangle to draw it in
string textToDraw = "This is a long piece of text that might need trimming and special alignment.";
Rectangle layoutRect = new Rectangle(50, 50, 200, 100);

// Define a Font and a Brush
Font font = new Font("Arial", 12);
Brush brush = new SolidBrush(Color.Black);

// Draw the string using the StringFormat object
graphics.DrawString(textToDraw, font, brush, layoutRect, sf);

// Dispose of the objects when done
sf.Dispose();
font.Dispose();
brush.Dispose();

Important Note:

Always remember to dispose of StringFormat objects when you are finished with them, especially in performance-critical applications, to release system resources.

See Also