C# 将Label变成有渐变背景色的圆角矩形

时间:2022-04-07 14:48:28

设置Label的属性BorderStyle = None;//这样才能看到效果

LabelPaint事件里调用如下方法:

private void label_Paint(object sender, PaintEventArgs e)

{

    DrawRoundRect(e.Graphics, label);

    DrawString(e.Graphics, label);

}

private void DrawRoundRect(Graphics graphics, Label label)

{

    float X = float.Parse(label.Width.ToString()) - 1;

    float Y = float.Parse(label.Height.ToString()) - 1;

    PointF[] points = {

        new PointF(2,     0),

        new PointF(X-2,   0),

        new PointF(X-1,   1),

        new PointF(X,     2),

        new PointF(X,     Y-2),

        new PointF(X-1,   Y-1),

        new PointF(X-2,   Y),

        new PointF(2,     Y),

        new PointF(1,     Y-1),

        new PointF(0,     Y-2),

        new PointF(0,     2),

        new PointF(1,     1)

        };

    GraphicsPath path = new GraphicsPath();

    path.AddLines(points);

    Pen pen = new Pen(Color.FromArgb(150, Color.Gray), 1);

    pen.DashStyle = DashStyle.Solid;

    graphics.DrawPath(pen, path);

    PathGradientBrush p = new PathGradientBrush(path);

    p.CenterColor = Color.White;

    Color[] color = { Color.LightGray };

    p.SurroundColors = color;

    graphics.FillPath(p, path);

}

private void DrawString(Graphics graphics, Label label)

{

    Font font = new Font("宋体", 10.0f, FontStyle.Regular);

    StringFormat stringFormat = new StringFormat();

    stringFormat.Alignment = StringAlignment.Center;

    stringFormat.LineAlignment = StringAlignment.Center;

    Brush brush = new SolidBrush(Color.Black);

    RectangleF rect = new RectangleF(0, 0, label.Width, label.Height);

    graphics.DrawString(label.Text, font, brush, rect, stringFormat);

}

原文:http://blog.sina.com.cn/s/blog_5421dfd20100f9br.html