using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace WinCustControls
{
public partial class UCWaterTank : UserControl
{
public UCWaterTank()
{
InitializeComponent();
SetStyle(ControlStyles.AllPaintingInWmPaint, true);//忽略窗口消息,减少闪烁
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);//绘制到缓冲区,减少闪烁
SetStyle(ControlStyles.UserPaint, true);//控件由其自身而不是操作系统绘制
SetStyle(ControlStyles.ResizeRedraw, true);//控件调整其大小时重绘
SetStyle(ControlStyles.SupportsTransparentBackColor, true);//支持透明背景
RectWidth = 2;
this.Size = new Size(100, 200);
}
float fRatio = 0.0f;
float fHeight = 0.0f;//实际水位高度
private RectangleF valueRect;//水位深度矩形
private int mValue;
//中心放射颜色
[DefaultValue(typeof(int), "0"), Description("当前水位值")]
public int Value
{
get { return mValue; }
set
{
if (value > maxValue)
mValue = maxValue;
else if (value < 0)
mValue = 0;
else
mValue = value;
UpdateHeight();//更新比例数 实际矩形区域
Invalidate();
}
}
private int maxValue = 100;
//中心放射颜色
[DefaultValue(typeof(int), "100"), Description("最大水位值")]
public int MaxValue
{
get { return maxValue; }
set
{
if (value < mValue)
maxValue = mValue;
else
maxValue = value;
UpdateHeight();//更新比例数 实际矩形区域
Invalidate();
}
}
private Color valueColor = Color.Blue;
[DefaultValue(typeof(Color), "Blue"), Description("水位深度颜色")]
public Color ValueColor
{
get { return valueColor; }
set
{
valueColor = value;
Invalidate();
}
}
private Color borderColor = Color.Gray;
[DefaultValue(typeof(Color), "Gray"), Description("水池的边框颜色")]
public Color BorderColor
{
get { return borderColor; }
set
{
borderColor = value;
Invalidate();
}
}
private int rectWidth = 1;
//中心放射颜色
[DefaultValue(typeof(int), "1"), Description("水池的边框粗细")]
public int RectWidth
{
get { return rectWidth; }
set
{
rectWidth = value;
UpdateHeight();//更新比例数 实际矩形区域
Invalidate();
}
}
///
/// 更新内部矩形的实际高度
///
private void UpdateHeight()
{
UpdateRatio();
//水位高度
fHeight = (float)Value * fRatio;
//水位的矩形结构
valueRect = new RectangleF(rectWidth, Height - fHeight - rectWidth, Width - 2 * rectWidth - 1, fHeight);
}
///
/// 计算水池高度与最大水位值之间比例值
///
private void UpdateRatio()
{
fRatio = (float)(Height - 2 * RectWidth) / (float)MaxValue;
}
protected override void OnSizeChanged(EventArgs e)
{
base.OnSizeChanged(e);
UpdateHeight();
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
Graphics g = e.Graphics;
g.SmoothingMode = SmoothingMode.AntiAlias;
//画边框线的pen对象
Pen pen = new Pen(new SolidBrush(borderColor), RectWidth);
Rectangle rect = new Rectangle(0, 0, this.Width - 1, Height - 1);
//外边框圆角矩形
GraphicsPath rectPath = PaintClass.GetRoundRectangle(rect, 5);
//填充水位
g.FillRectangle(new SolidBrush(ValueColor), valueRect);
//画边框
g.DrawPath(pen, rectPath);
}
}
}