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

设置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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值