views:

57

answers:

2

Hi,

I have a list of strings which I paint on an axis. I want to rotate the strings (again, they should stay on the same horizontal axis when rotated). I am trying to use the following code:

namespace DrawString
{
    struct StringData
    {
        public string StringName;
        public int X;
        public int Y;
    }

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        Font mFont = new Font("Arial", 10.0f, FontStyle.Bold);
        List<StringData> data = new List<StringData> { new StringData() { StringName = "Label1", X = 10, Y = 30 },
                                                     new StringData() { StringName = "Label2", X = 130, Y = 30 }};

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            foreach (var str in data)
            {
                e.Graphics.RotateTransform(30);
                e.Graphics.DrawString(str.StringName, mFont, new SolidBrush(Color.Black), new Point(str.X, str.Y));
                e.Graphics.ResetTransform();
            }
        }
    }
}

But it doesn't work since the Graphics is rotating for both of the strings at once, causing one string to be higher than the other. How can I rotate them individually using the center of the string as its rotation axis?

+1  A: 

It sounds like you are describing something like this:

private void Form1_Paint(object sender, PaintEventArgs e)
{
    foreach (var str in data)
    {
        e.Graphics.TranslateTransform(str.X, str.Y);
        e.Graphics.RotateTransform(30);
        e.Graphics.DrawString(str.StringName, mFont, new SolidBrush(Color.Black), new Point(0, 0));
        e.Graphics.ResetTransform();
    }
}

This snippet first translates, then rotates, draws the string at the transformed origin, and then resets. Both strings are rotated at the same angle on the same X axis, but originate from different points.

kbrimington
Thanks a lot. It worked.
Ioga3
A: 

What about

        private void Form1_Paint(object sender, PaintEventArgs e) 
        { 
            e.Graphics.RotateTransform(30);
            foreach (var str in data) 
            { 
                e.Graphics.DrawString(str.StringName, mFont, new SolidBrush(Color.Black), new Point(str.X, str.Y)); 
            }
            e.Graphics.ResetTransform();  
        } 

After rotating the plane, you will draw the strings in position

Tor