Windows 窗体中的 C# 垂直标签 [英] C# vertical label in a Windows Forms

查看:33
本文介绍了Windows 窗体中的 C# 垂直标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 Windows 窗体中垂直显示标签?

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

推荐答案

标签很容易,你所要做的就是覆盖 Paint 事件并垂直绘制文本.请注意,GDI 针对水平绘制文本进行了优化.如果你旋转文本(即使你旋转了 90 度的倍数),它看起来会明显更糟.

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.

一些用于绘制带有垂直文本的自定义控件的 C# 代码.请注意,如果文本不是水平的,则 ClearType 文本永远不会起作用:

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

这篇关于Windows 窗体中的 C# 垂直标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆