winform控件开发一之复合控件开发(4)液位计(Liquid Level)

发布时间 2023-06-26 14:29:39作者: hanzq_go

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

 实现代码如下:

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

namespace 各种C_sharp功能测试
{
    /// <summary>
    /// 液位显示,棒图
    /// </summary>
    public partial class LiquidLevel : Control
    {
        public LiquidLevel()
        {
            InitializeComponent();
            SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
            SetStyle(ControlStyles.ResizeRedraw, true);
            SetStyle(ControlStyles.SupportsTransparentBackColor, true);
        }

        //液位高度百分比,输入范围0-100%
        private float _value = 0.5f;

        public float Value
        {
            get { return _value; }
            set { _value = 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执行效果相同

            //第一种方法
            //g.DrawRectangle(new Pen(Color.Gray,1), new Rectangle(0,0,Width-1,Height-1));           
            //g.FillRectangle(new SolidBrush(Color.LightGray), new Rectangle(1, 1, Width - 3, Height - 3));             
            //g.FillRectangle(new SolidBrush(Color.Green),new RectangleF(1,Height-2-(Height-3)*Value,Width-3,(Height-3)*Value));

            //第二种方法
            Color c;
            if (Value <= 0.1f | Value >= 0.9)
            {
                c = Color.Red;
            }
            else
            {
                c = Color.Green;
            }
            g.FillRectangle(new SolidBrush(Color.LightGray), this.ClientRectangle);
            g.FillRectangle(new SolidBrush(c), new RectangleF(0, Height - Height * Value, Width, Height * Value));
            g.DrawRectangle(new Pen(Color.Gray, 1), new Rectangle(0, 0, Width - 1, Height - 1));
        }
    }
}