C# Vertical Label in a Windows Forms

Winform label rotate properties?

Unfortunately, you cannot rotate text in a WinForms label.
If you really want to do it, you have to handle the Paint event and write code to rotate the text.

How can I flip/rotate the label in C#/Windows Forms?

Create a class, newlabel, which can rotate its Text on any angle specified by the user.

extend label class& override paint method

You can use it by code or simply dragging from the ToolBox.

using System.Drawing;

class newLabel : System.Windows.Forms.Label
{
public int RotateAngle { get; set; }
public string NewText { get; set; }
protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
{
Brush b =new SolidBrush(this.ForeColor);
e.Graphics.TranslateTransform(this.Width / 2, this.Height / 2);
e.Graphics.RotateTransform(this.RotateAngle);
e.Graphics.DrawString(this.NewText, this.Font,b , 0f, 0f);
base.OnPaint(e);
}
}

Now drag this custom control to be used into your form.

You have to set the below properties.

newlbl.Text = "";           
newlbl.AutoSize = false;
newlbl.NewText = "ravindra";
newlbl.ForeColor = Color.Green;
newlbl.RotateAngle = -90;

Change angle as required by simply changing the RotateAngle property.

How do I rotate a label in C#?

You will need to write your own or use a custom control.

A The Code Project article you can start with is Customized Text - Orientated Controls in C# - Part I (Label Control). This contains extra functionality, so you should be able to trim it down if you'd like.

And here is some code from it that is of interest:

/// <summary>
/// This is a lable, in which you can set the text in any direction/angle
/// </summary>

#region Orientation

//Orientation of the text

public enum Orientation
{
Circle,
Arc,
Rotate
}

public enum Direction
{
Clockwise,
AntiClockwise
}

#endregion

public class OrientedTextLabel : System.Windows.Forms.Label
{
#region Variables

private double rotationAngle;
private string text;
private Orientation textOrientation;
private Direction textDirection;

#endregion

#region Constructor

public OrientedTextLabel()
{
//Setting the initial condition.
rotationAngle = 0d;
textOrientation = Orientation.Rotate;
this.Size = new Size(105,12);
}

#endregion

#region Properties

[Description("Rotation Angle"),Category("Appearance")]
public double RotationAngle
{
get
{
return rotationAngle;
}
set
{
rotationAngle = value;
this.Invalidate();
}
}

[Description("Kind of Text Orientation"),Category("Appearance")]
public Orientation TextOrientation
{
get
{
return textOrientation;
}
set
{
textOrientation = value;
this.Invalidate();
}
}

[Description("Direction of the Text"),Category("Appearance")]
public Direction TextDirection
{
get
{
return textDirection;
}
set
{
textDirection = value;
this.Invalidate();
}
}

[Description("Display Text"),Category("Appearance")]
public override string Text
{
get
{
return text;
}
set
{
text = value;
this.Invalidate();
}
}

#endregion

#region Method

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

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;
}

//Setting the text according to the selection
switch (textOrientation)
{
case Orientation.Arc:
{
//Arc angle must be get from the length of the text.
float arcAngle = (2*width/radius)/text.Length;
if(textDirection == Direction.Clockwise)
{
for (int i=0; i<text.Length; i++)
{
graphics.TranslateTransform(
(float)(radius*(1 - Math.Cos(arcAngle*i + rotationAngle/180 * Math.PI))),
(float)(radius*(1 - Math.Sin(arcAngle*i + rotationAngle/180*Math.PI))));
graphics.RotateTransform((-90 + (float)rotationAngle + 180*arcAngle*i/(float)Math.PI));
graphics.DrawString(text[i].ToString(), this.Font, textBrush, 0, 0);
graphics.ResetTransform();
}
}
else
{
for (int i=0; i<text.Length; i++)
{
graphics.TranslateTransform(
(float)(radius*(1 - Math.Cos(arcAngle*i + rotationAngle/180*Math.PI))),
(float)(radius*(1 + Math.Sin(arcAngle*i + rotationAngle/180*Math.PI))));
graphics.RotateTransform((-90 - (float)rotationAngle - 180*arcAngle*i/(float)Math.PI));
graphics.DrawString(text[i].ToString(), this.Font, textBrush, 0, 0);
graphics.ResetTransform();
}
}
break;
}
case Orientation.Circle:
{
if (textDirection == Direction.Clockwise)
{
for(int i=0;i<text.Length;i++)
{
graphics.TranslateTransform(
(float)(radius*(1 - Math.Cos((2*Math.PI/text.Length)*i + rotationAngle/180*Math.PI))),
(float)(radius*(1 - Math.Sin((2*Math.PI/text.Length)*i + rotationAngle/180*Math.PI))));
graphics.RotateTransform(-90 + (float)rotationAngle + (360/text.Length)*i);
graphics.DrawString(text[i].ToString(), this.Font, textBrush, 0, 0);
graphics.ResetTransform();
}
}
else
{
for(int i=0;i<text.Length;i++)
{
graphics.TranslateTransform(
(float)(radius*(1 - Math.Cos((2*Math.PI/text.Length)*i + rotationAngle/180*Math.PI))),
(float)(radius*(1 + Math.Sin((2*Math.PI/text.Length)*i + rotationAngle/180*Math.PI))));
graphics.RotateTransform(-90 - (float)rotationAngle - (360/text.Length)*i);
graphics.DrawString(text[i].ToString(), this.Font, textBrush, 0, 0);
graphics.ResetTransform();
}

}
break;
}

case Orientation.Rotate:
{
//For rotation, who about rotation?
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();

break;
}
}
}
#endregion
}

How to make textbox rotated 90 (vertical) during typing?

Your question got me curious! So I tried to implement something. And turns out it is kinda complicated to do in winforms

Here is my shot, you will need to improve it, but it works(ish). The idea is to paint a white background to hide the text draw by the TextBox, then draw it vertically.

Result:

TextBox with vertical text.

Note that you can improve the result using another method to draw the text — this code for example.

Code:

using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

public class VerticalTextBox : TextBox
{
private bool bFlip = true;

public VerticalTextBox()
{
Multiline = true;
SetStyle(ControlStyles.UserPaint, true);
TextChanged += OnTextChanged;
}

private void OnTextChanged(object sender, EventArgs eventArgs)
{
Invalidate(); // repaint all
}

protected override void OnPaintBackground(PaintEventArgs e)
{
var g = e.Graphics;
g.FillRectangle(new SolidBrush(BackColor), ClientRectangle);

var stringFormat = new StringFormat {
Alignment = StringAlignment.Center,
Trimming = StringTrimming.None,
FormatFlags = StringFormatFlags.DirectionVertical
};

Brush textBrush = new SolidBrush(ForeColor);

var storedState = g.Transform;

if (bFlip)
{
g.RotateTransform(180f);
g.TranslateTransform(-ClientRectangle.Width,-ClientRectangle.Height);
}
g.DrawString(
Text,
Font,
textBrush,
ClientRectangle,
stringFormat);

g.Transform = storedState;
}

[Description("When this parameter is true the VLabel flips at 180 degrees."),Category("Appearance")]
public bool Flip180
{
get => bFlip;
set
{
bFlip = value;
Invalidate();
}
}
}

References

  1. VerticalLabel

  2. SetStyle to tell the TextBox to call the Paint event.

BETTER(?) ALTERNATIVES

  1. To get better results, in winforms, I recommend you to learn about the FastColoredTextBox and use it.

  2. Migrate to WPF, apparently is easy.

Label Alignment in c# windows form

Vertical text isn’t hard in C#. Simply apply a RotateTransform to a Graphics object and draw the text using DrawString.

using MySql.Data.MySqlClient;
using System;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Windows.Forms;

namespace Vertical_label
{
public partial class Vertical_label: Form
{
public Vertical_label()
{
InitializeComponent();
}
private void label1_Paint(object sender, PaintEventArgs e)
{

e.Graphics.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;

using (Font the_font = new Font("Microsoft Sans Serif", 10 , FontStyle.Bold))
{
int x = 5, y = 50;
DrawRotatedTextAt(e.Graphics, -90, "DATA", x, y, the_font, Brushes.Black);

}
}
private void DrawRotatedTextAt(Graphics gr, float angle, string txt, int x, int y, Font the_font, Brush the_brush)
{
// Save the graphics state.
GraphicsState state = gr.Save();
gr.ResetTransform();

// Rotate.
gr.RotateTransform(angle);

// Translate to desired position. Be sure to append
// the rotation so it occurs after the rotation.
gr.TranslateTransform(x, y, MatrixOrder.Append);

// Draw the text at the origin.
gr.DrawString(txt, the_font, the_brush, 0, 0);

// Restore the graphics state.
gr.Restore(state);
}
}
}
}

Result:

Sample Image

Keep a Control vertically and horizontally at center of its container

Sample Image

We can achive this by simple steps

  • Set Label Anchor to Left and Right
  • Set Label AutoSize to false ;
  • Set Label TextAlign to MiddleCenter;

now Place label middle of panel.

   int x = (panel1.Size.Width - label1.Size.Width) / 2;
label1.Location = new Point(x, label1.Location.Y);

Add Items vertically in Panel

You have to specify the location

 Label l = new Label();
l.Text = "Hello1";
l.Location = new Point(0, 0);
Label ll = new Label();
ll.Text = "Hello2";
l.Location = new Point(0, 20);
ll.Margin = new Padding(50, 50, 0, 0);
ShowAllItemContainer.Controls.Add(l);
ShowAllItemContainer.Controls.Add(ll);

Also you can achieve it using flowlayout panel

Label l = new Label();
l.Text = "Hello1";
Label ll = new Label();
ll.Text = "Hello2";
flowLayoutPanel1.Controls.Add(l);
flowLayoutPanel1.Controls.Add(ll);
flowLayoutPanel1.FlowDirection = FlowDirection.TopDown;

.NET Winforms Vertical Progress Bar Text

You need to use StringFormat to draw your string in vertical, using the flag. Try the following in your WndProc method:

    protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == 0x000F)
{
using (Graphics graphics = CreateGraphics())
using (SolidBrush brush = new SolidBrush(ForeColor))
{
StringFormat format = new StringFormat(
StringFormatFlags.DirectionVertical);

SizeF textSize = graphics.MeasureString(Text, Font);
graphics.DrawString(
Text, Font, brush,
(Width / 2 - textSize.Height / 2),
(Height / 2 - textSize.Width / 2),
format);
}
}
}


Related Topics



Leave a reply



Submit