重绘按钮,做个自己的圆形LED指示灯

        最近为了做个上位机触摸屏软件,客户要求和工业触摸屏界面一样,要求指示灯做成圆形的。将C#中的按钮外形重绘,加入了从外到内的渐变功能,代码如下:

        实际应用中,添加LED控件后,修改属性type的值,指示灯的颜色就会自动切换。

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Test
{
    class Led : Button
    {
        private Color ledColor = Color.Silver;
        private bool type_;

        /// 
        /// 指示灯颜色切换
        /// 
        public bool type
        {
            get
            {
                return type_;
            }
            set
            {
                if(this.type_ != value)
                {
                    this.type_ = value;
                    if(!this.type_)
                        ledColor = Color.Silver;
                    else
                        ledColor = Color.Lime;

                    //强制重绘
                    this.Invalidate();
                }
            }
        }

        

        public Led()
        {
            this.Paint += new System.Windows.Forms.PaintEventHandler(this.Ovalshape_Paint);
        }


        private void Ovalshape_Paint(object sender, PaintEventArgs e)
        {
            //重绘时 画出中心放射颜色的圆形
            GraphicsPath path = new GraphicsPath();
            path.AddEllipse(0, 0, this.Size.Width, this.Size.Height);
            PathGradientBrush pthGrBrush = new PathGradientBrush(path);

            //中心的颜色
            pthGrBrush.CenterColor = Color.White;
            //边缘的颜色
            Color[] colors = new Color[] { this.ledColor };
            pthGrBrush.SurroundColors = colors;
            e.Graphics.FillEllipse(pthGrBrush, 0, 0, this.Size.Width, this.Size.Height);

            path.Dispose();
            pthGrBrush.Dispose();
        }




        protected override void OnPaint(PaintEventArgs pevent)
        {
            //使控件边界也为圆形
            GraphicsPath gp = new GraphicsPath();
            gp.AddEllipse(0, 0, this.Width, this.Height);

            this.Region = new System.Drawing.Region(gp);
            base.OnPaint(pevent);
            base.OnPaint(pevent);

            gp.Dispose();
        }
    }
}

你可能感兴趣的:(C#,c#,指示灯,控件重绘)