How do I draw verticle text on image using GDI+?

How do I draw vertical text on image using GDI+? I can not find any thing in GDI+ which allows me to draw vertical text.

Graphics class does not have any method to directly draw vertical text on image, however you can draw regular text on image and rotate that image to display vertical text.

Download Code | Run Sample

<%@ WebHandler Language="C#" Class="VerticalText"%>

using System;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Text;

public class  VerticalText : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType ="image/gif";

        Bitmap bitmap = new Bitmap(100, 300);
        Graphics g = Graphics.FromImage(bitmap);
        g.TextRenderingHint = TextRenderingHint.AntiAlias;
        g.Clear(Color.White);
        g.DrawRectangle(Pens.Black, 0, 0
            , bitmap.Width -1, bitmap.Height-1);
        DrawStringVertical(g, new RectangleF(10,10,80,280)
            , "Vertical Text", new Font(FontFamily.GenericSerif,20),
            Brushes.Black);

        bitmap.Save(context.Response.OutputStream, ImageFormat.Gif);
        
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

    public static void DrawStringVertical(Graphics g
        , RectangleF r, string Text, Font f, Brush b) {
        
        // Set string format and alignment.
        StringFormat sf = new System.Drawing.StringFormat();
        sf.Alignment = StringAlignment.Center;
        sf.LineAlignment = StringAlignment.Center;
        
        // create temp image
        Bitmap tempImage = new Bitmap((int)r.Height, (int)r.Width);
        
        // now draw text on image.
        Graphics tempGraphics = Graphics.FromImage(tempImage);
        tempGraphics.TextRenderingHint = g.TextRenderingHint;
        tempGraphics.DrawString(Text, f, b
            , new RectangleF(0, 0, tempImage.Width,tempImage.Height), sf);
        tempImage.RotateFlip(RotateFlipType.Rotate270FlipNone);

        // now draw temp image on original image
        g.DrawImage(tempImage, r.X, r.Y);
        tempGraphics.Dispose();
        tempImage.Dispose();
    }
}
Bookmark with:
Technorati   Digg   Delicious   StumbleUpon   Facebook
My name is Jigar Desai I share my ideas on this site and you can contact me by filling contact form.

Categories