水桶
1 效果图


2 代码编写
/// <summary> /// 水桶 /// </summary> public partial class UCWaterTank : UserControl { public UCWaterTank() { InitializeComponent(); this.SetStyle(ControlStyles.AllPaintingInWmPaint, true); this.SetStyle(ControlStyles.DoubleBuffer, true); this.SetStyle(ControlStyles.ResizeRedraw, true); this.SetStyle(ControlStyles.Selectable, true); this.SetStyle(ControlStyles.SupportsTransparentBackColor, true); this.SetStyle(ControlStyles.UserPaint, true); RectWidth = 2; // this.SizeChanged += UCWaterTank_SizeChanged; this.Size = new Size(100, 200); //valueRect = new Rectangle(this.RectWidth, this.Location.Y + (this.Height - this.Value), this.Width - 2 * RectWidth, this.Value); } private RectangleF valueRect; int m_value; [Description("当前值"), Category("自定义")] public int Value { set { if (value > m_maxValue) m_value = m_maxValue; else if (value < 0) m_value = 0; else m_value = value; //if (ValueChanged != null) // ValueChanged(this, null); Refresh(); } get { return m_value; } } private int m_maxValue = 100; [Description("最大值"), Category("自定义")] public int MaxValue { get { return m_maxValue; } set { if (value < m_value) m_maxValue = m_value; else m_maxValue = value; Refresh(); } } [Description("值颜色"), Category("自定义")] private Color valueColor = Color.Blue; public Color ValueColor { get { return valueColor; } set { valueColor = value; Refresh(); } } [Description("边框宽度"), Category("自定义")] private int rectWidth = 1; public int RectWidth { get { return rectWidth; } set { rectWidth = value; Refresh(); } } [Description("边框颜色"), Category("自定义")] private Color borderColor = Color.Blue; public Color BorderColor { get { return borderColor; } set { borderColor = value; Refresh(); } } //void UCWaterTank_SizeChanged(object sender, EventArgs e) //{ // valueRect = new Rectangle(this.RectWidth, this.Location.Y + (this.Height - this.Value), this.Width - 2 * RectWidth, this.Value); //} protected override void OnSizeChanged(EventArgs e) { base.OnSizeChanged(e); float f = (float)this.Height / (float)MaxValue; float fheight = (float)this.Value * f; valueRect = new RectangleF(this.RectWidth, this.Location.Y + (this.Height - fheight), this.Width - 2 * RectWidth, fheight); } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); Graphics g = e.Graphics; g.SmoothingMode = SmoothingMode.AntiAlias; Pen pen = new Pen(new SolidBrush(BorderColor), (float)RectWidth); Rectangle rect = new Rectangle(0, 0, this.Width-1, this.Height-1); g.DrawRectangle(pen, rect); float f = (float)this.Height / (float)MaxValue; float fheight = (float)this.Value * f; valueRect = new RectangleF(this.RectWidth, (this.Height - fheight), this.Width - 2 * RectWidth, fheight); g.FillRectangle(new SolidBrush(ValueColor), valueRect); } }

浙公网安备 33010602011771号