winform控件开发一之复合控件开发(3)调节阀(regulate valve)

发布时间 2023-06-21 15:56:03作者: hanzq_go

使用自定义控件,实现一个调节阀,显示效果如下:

 实现代码如下:

using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;

namespace 各种C_sharp功能测试
{
    public partial class RegulateValve : Control
    {
        public RegulateValve()
        {
            InitializeComponent();
            SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
            SetStyle(ControlStyles.ResizeRedraw, true);
            SetStyle(ControlStyles.SupportsTransparentBackColor, true);
        }
        //阀门开度
        private float openValue;

        public float OpenValue
        {
            get { return openValue; }
            set { openValue = value; Invalidate(); }
        }


        //阀门开时显示的颜色
        private Color openColor = Color.Green;

        public Color OpenColor
        {
            get { return openColor; }
            set { openColor = value; Invalidate(); }
        }

        //阀门关时显示的颜色
        private Color closeColor = Color.Red;

        public Color CloseColor
        {
            get { return closeColor; }
            set { closeColor = value; Invalidate(); }
        }
        protected override void OnPaint(PaintEventArgs pe)
        {
            base.OnPaint(pe);
            //获取绘图对象
            Graphics g = pe.Graphics;
            //呈现质量设置为高质量
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;//HighQuality和AntiAlias执行效果相同

            //第一步绘制上方扇形
            GraphicsPath path1 = new GraphicsPath();
            Rectangle rect = new Rectangle(Width / 4, 0, Width / 2, Height * 2 / 3);
            path1.AddArc(rect, 180f, 180f);
            path1.CloseFigure();
            g.FillPath(new SolidBrush(OpenValue > 0 ? openColor : closeColor), path1);
            //第二步绘制中间竖线
            g.DrawLine(new Pen(Color.Black, 2f), new Point(Width / 2, Height / 3), new Point(Width / 2, Height * 2 / 3));
            //第三步绘制下方8字三角形
            GraphicsPath path3 = new GraphicsPath();
            Point p1 = new Point(0, Height / 3);
            Point p2 = new Point(Width - 1, Height / 3);
            Point p3 = new Point(Width - 1, Height - 1);
            Point p4 = new Point(0, Height - 1);
            path3.AddLine(p1, p3);
            path3.AddLine(p3, p2);
            path3.AddLine(p2, p4);
            path3.AddLine(p4, p1);
            path3.CloseFigure();
            g.FillPath(new SolidBrush(OpenValue > 0 ? openColor : closeColor), path3);
        }
    }
}