a long string that will wrap and centered both vertically and horizontally

image_pdfimage_print
   
 
    
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

public class Form1 : Form {

    protected override void OnPaint(PaintEventArgs e) {
    Graphics g = e.Graphics;
    g.FillRectangle(Brushes.White, this.ClientRectangle);

    String s = "This is a long string that will wrap. ";
    s += "It will be centered both vertically and horizontally.";
    Font f = new Font("Arial", 12);
    StringFormat sf = new StringFormat();

    sf.Alignment = StringAlignment.Center;        
    sf.LineAlignment = StringAlignment.Center;    

    Rectangle r = new Rectangle(10, 10, 300, f.Height * 4);
    g.DrawRectangle(Pens.Black, r);
    g.DrawString(s, f, Brushes.Black, r, sf);
    f.Dispose();
    }
    public static void Main() {
        Application.Run(new Form1());
    }
}

    


This entry was posted in 2D Graphics. Bookmark the permalink.