C# vertical label in a Windows Forms

前端 未结 9 1426
独厮守ぢ
独厮守ぢ 2020-11-28 11:40

Is it possible to display a label vertically in a Windows Forms?

9条回答
  •  北海茫月
    2020-11-28 12:41

    Labels are easy, all you have to do is override the Paint event and draw the text vertically. Do note that GDI is optimised for Drawing text horizontally. If you rotate text (even if you rotate through multiples of 90 degrees) it will looks notably worse.

    Perhaps the best thing to do is draw your text (or get a label to draw itself) onto a bitmap, then display the bitmap rotated.

    Some C# code for drawing a Custom Control with vertical text. Note that ClearType text NEVER works if the text is not horizontal:

    using System;
    using System.Drawing;
    using System.Drawing.Drawing2D;
    using System.Windows.Forms;
    
    
    public partial class VerticalLabel : UserControl
    {
        public VerticalLabel()
        {
            InitializeComponent();
        }
    
        private void VerticalLabel_SizeChanged(object sender, EventArgs e)
        {
            GenerateTexture();
        }
    
        private void GenerateTexture()
        {
            StringFormat format = new StringFormat();
            format.Alignment = StringAlignment.Center;
            format.LineAlignment = StringAlignment.Center;
            format.Trimming = StringTrimming.EllipsisCharacter;
    
            Bitmap img = new Bitmap(this.Height, this.Width);
            Graphics G = Graphics.FromImage(img);
    
            G.Clear(this.BackColor);
    
            SolidBrush brush_text = new SolidBrush(this.ForeColor);
            G.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixelGridFit;
            G.DrawString(this.Name, this.Font, brush_text, new Rectangle(0, 0, img.Width, img.Height), format);
            brush_text.Dispose();
    
            img.RotateFlip(RotateFlipType.Rotate270FlipNone);
    
            this.BackgroundImage = img;
        }
    }
    

提交回复
热议问题