- 1 year ago
How to Rotate Label 90 Degrees in C#
Comment
1 / 1
In C#, you can rotate a label 90 degrees using the RotateTransform
method of the Graphics
class. Here's an example code snippet:
csharpprivate void Form1_Load(object sender, EventArgs e)
{
// Create a new label
Label label1 = new Label();
label1.Text = "My Label";
label1.AutoSize = true;
label1.Location = new Point(50, 50);
// Rotate the label 90 degrees
label1.Paint += new PaintEventHandler(label1_Paint);
// Add the label to the form
this.Controls.Add(label1);
}
private void label1_Paint(object sender, PaintEventArgs e)
{
// Get the label to rotate
Label label = sender as Label;
// Create a new graphics object
Graphics g = e.Graphics;
// Rotate the graphics object 90 degrees clockwise
g.RotateTransform(90);
// Translate the graphics object to draw the label
g.TranslateTransform(0, -label.Width);
// Draw the label
g.DrawString(label.Text, label.Font, new SolidBrush(label.ForeColor), 0, 0);
}
In this code, a new Label
control is created with the text "My Label" and placed at location (50, 50) on the form. The Paint
event of the label is then handled by the label1_Paint
method, which rotates the graphics object by 90 degrees, translates it to draw the label, and then draws the label text using the DrawString
method.
Note that the AutoSize
property of the label should be set to true
to ensure that the label is rotated correctly.