views:

44

answers:

2

Hi,

I am trying to rotate a label through 90 degrees. At the moment I can take the text from the label and rotate that, but what I want to do is actually rotate a label of my choice, or if I were to be really flashy, lets say a button control. So using the code below, how can I modify it so that I can feed it a control and get it to rotate it?

protected override void OnPaint(PaintEventArgs e)
    {
        Graphics graphics = e.Graphics;

        string text = label4.Text;

        StringFormat stringFormat = new StringFormat();
        stringFormat.Alignment = StringAlignment.Center;
        stringFormat.Trimming = StringTrimming.None;

        Brush textBrush = new SolidBrush(this.ForeColor);

        //Getting the width and height of the text, which we are going to write
        float width = graphics.MeasureString(text, this.Font).Width;
        float height = graphics.MeasureString(text, this.Font).Height;

        //The radius is set to 0.9 of the width or height, b'cos not to 
        //hide and part of the text at any stage
        float radius = 0f;
        if (ClientRectangle.Width < ClientRectangle.Height)
        {
            radius = ClientRectangle.Width * 0.9f / 2;
        }
        else
        {
            radius = ClientRectangle.Height * 0.9f / 2;
        }
        int rotationAngle = 90;
        double angle = (rotationAngle / 180) * Math.PI;
        graphics.TranslateTransform(
            (ClientRectangle.Width + (float)(height * Math.Sin(angle)) - (float)(width * Math.Cos(angle))) / 2,
            (ClientRectangle.Height - (float)(height * Math.Cos(angle)) - (float)(width * Math.Sin(angle))) / 2);
        graphics.RotateTransform((float)rotationAngle);
        graphics.DrawString(text, this.Font, textBrush, 0, 0);
        graphics.ResetTransform();        
    }
A: 

You could use WPF instead of WinForms...then its a simple transform ;)

KrisTrip
I did, but that opened up a whole new can of worms...
flavour404
+2  A: 

Standard windows forms controls (such as a label and button) are rendered by the operating system itself, windows forms doesn't do the actual drawing.

Therefore, unfortunately, you have no control over aspects such as rotation and scaling with these sorts of controls. This is just a limitation of Windows Forms itself and is one of the major reasons Microsoft created WPF.

WPF controls are entirely rendered by WPF (using DirectX behind the scenes). WPF supports all the standard 2D (and 3D) transaformations such as scaling, rotation and translation.

Altrrnatively in windows forms you could create a custom control that you render using GDI+ and can rotate and scale as required. Of course now you're doing all the work yourself which it seems is not what you want.

Ash