如何让温度、湿度、压力等有量程的监控值如仪表盘(DashBoard)一样显示?
思路(GDI绘图):
定义属性:(仪表盘的半径、颜色、间隙;刻度圆的半径、颜色、字体;指针的颜色、占比;文本的字体、占比;)
绘制图形:(半圆、刻度、指针、中心、文本)
定义属性(将以上属性挨个敲完)
//量程属性(Font、Color、Float、Int、String、Bool)
private float range = 180.0f;
[Browsable(true)]
[Category("布局_G")]
[Description("量程")]
public float Range
{
get { return range; }
set
{
if (value < 0.0f) return;
range = value; this.Invalidate();
}
}
定义字段
private Graphics g; //画布
private Pen p; //笔-绘制线条、曲线
private SolidBrush sb; //笔(填充)-填充矩形、路径
private int width;
private int height;
仪表盘外环
//画外环的三个圆弧(DrawArc)
float angle = (180.0f - gapAngle * 2) / 3; //定义角度
RectangleF rec = new RectangleF(10, 10, this.width - 20, this.width - 20); //定义坐标、宽、高
p = new Pen(colorCircle1, outThickness);
g.DrawArc(p, rec, -180.0f, angle); //第一个弧
p = new Pen(colorCircle2, outThickness);
g.DrawArc(p, rec, -180.0f + angle + gapAngle, angle); //第二个弧
p = new Pen(colorCircle3, outThickness);
g.DrawArc(p, rec, -180.0f + angle * 2.0f + gapAngle + 2.0f, angle); //第三个弧
仪表盘刻度
g.TranslateTransform(this.width * 0.5f, this.width * 0.5f);
for (int i = 0; i < 4; i++)
{
float actualAngle = -180.0f + 60.0f * i;
double x1 = Math.Cos(actualAngle * Math.PI / 180);
double y1 = Math.Sin(actualAngle * Math.PI / 180);
float x = Convert.ToSingle(this.width * scaleProportion * 0.5f * x1);
float y = Convert.ToSingle(this.width * scaleProportion * 0.5f * y1);
StringFormat sf = new StringFormat();
if (i > 1)
{
x = x - 60;
sf.Alignment = StringAlignment.Far;
}
else
{
sf.Alignment = StringAlignment.Near;
}
//刻度的坐标,宽,高
rec = new RectangleF(x, y, 60, 20);
sb = new SolidBrush(scaleColor);
if (range % 6 == 0)
{
g.DrawString((range / 3 * i).ToString(), scaleFont, sb, rec, sf);
}
else
{
g.DrawString((range / 3 * i).ToString("f1"), scaleFont, sb, rec, sf);
}
}
仪表盘中心点
//画中心(FillEllipse)
g.FillEllipse(new SolidBrush(pointColor), new RectangleF(-centerRadius, -centerRadius, centerRadius * 2.0f, centerRadius * 2.0f));
仪表盘指针
//画指针(DrawLine)
p = new Pen(pointColor, 3.0f); //定义指针颜色、宽度
float sweepAngle = currentValue / range * 180.0f; //划过的角度
float z = this.width * 0.5f * scaleProportion - outThickness * 0.5f - 20.0f; //指针长度
g.RotateTransform(90.0f); //默认开始角度
g.RotateTransform(sweepAngle);
g.DrawLine(p, new PointF(0, 0), new PointF(0, z)); //画一条线
下标文本标签
//写文本(DrawString)
g.RotateTransform(-sweepAngle);
g.RotateTransform(-90.0f); //指定初始角度
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
rec = new RectangleF(this.width * (-0.5f), this.height * textProportion - 0.5f * this.width, this.width, this.height * (1.0f - this.scaleProportion));
string val = TextPrefix + currentValue.ToString() + "" + textUnit ; //指定字符串
g.DrawString(val, textFont, new SolidBrush(textColor), rec, sf);
最后生成(自定义各种监控值显示)