Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing vertically stacked text in WinForms

Preferably using a Graphics object, how do you draw a string so that the characters are still oriented normally, but are stacked vertically?

like image 850
xyz Avatar asked Oct 05 '09 16:10

xyz


3 Answers

Just split the string into characters and draw each one adding the line height of your font to your Y-axis variable:

    protected override void OnPaint(PaintEventArgs e)
    {
        float x = 10.0F;
        float y = 10.0F;

        string drawString = "123";

        using(SolidBrush brush = new SolidBrush(Color.Black))
        using (Font drawFont = new Font("Arial", 16))
        {
            foreach (char c in drawString.ToCharArray())
            {
                PointF p = new PointF(x, y);
                e.Graphics.DrawString(c.ToString(), drawFont, brush, p);

                y += drawFont.Height;
            }
        }
        base.OnPaint(e);
    }
like image 112
scottm Avatar answered Oct 22 '22 22:10

scottm


Here is an example project that does vertical Text. Also has some comments about text alignment.

From the example, you can use the StringAlignment.Center to center the characters and pass it to the last parameter of the DrawString call.

    protected override void OnPaint(PaintEventArgs e) 
    { 
        float x = 10.0F;
        float y = 10.0F;
        Font drawFont = new Font("Arial", 16);
        SolidBrush drawBrush = new SolidBrush(Color.Black);
        StringFormat sf = new StringFormat();
        sf.Alignment = StringAlignment.Center;
        foreach (char c in Text.ToCharArray())
        { 
            PointF p = new PointF(x, y);
            e.Graphics.DrawString(c.ToString(), drawFont, drawBrush, p, sf);
            y += drawFont.Height;
        }
    }
like image 20
SwDevMan81 Avatar answered Oct 22 '22 20:10

SwDevMan81


If you're already using the right bounding box, I'd write a function that simply injected '\n's.

like image 1
overslacked Avatar answered Oct 22 '22 20:10

overslacked