TeeChart控件实现颜色渐变效果
效果图如下:
问题来源
公司的一个桥隧项目其中有个打分功能,领导觉得显示分数不友好,要改成颜色渐变条,然后上面有个指针指示现在处于什么预警状态下,颜色由绿->黄->橙->红依次渐变,预警值区间设定为:
0-0.4:绿到黄渐变。
0.4-0.8:黄到橙渐变。
0.8-1:橙到红渐变。
由于时间紧,想寻找是否有类似的控件可以直接使用,结果没有。所以只好自己写一个,思路是借用TeeChart控件的ColorGrid功能。
生成渐变色
绿色RGB(0,255,0), 黄色RGB(255,255,0), 橙色RGB(255,165,0), 红色RGB(255,0,0)
绿色->黄色:R由0->255 线性过渡
黄色->橙色:G由255->165 线性过渡
橙色->红色:G由165->0 线性过渡
既然属于线性过渡,所以他们之间的关系属于等比关系。拿绿色->黄色举例,假设当前的预警值为V,该预警值对应的R值设为X,此时就存在四种关系:
- 预警值:0-0.4 minV – maxV
- 当前值:0-V minV – V
- 总R值变化:0-255 minColor – maxColor
- 预警值R值变化:0-X minColor – X
SO:列出一个等比公式:(maxV – minV)/ (V – minV) = (maxColor – minColor) / (X – minColor) ;
设 DValue = maxV – minV
则 X = (V – minV) * (maxColor – minColor) / DValue + minColor。
所以求X代码如下:
1 2 3 4 |
private static int GetRGB(double v, double minv, int maxColor, int minColor, double dValue) { return Convert.ToInt32((maxColor - minColor) * (v - minv) / dValue + minColor); } |
根据预警值求对应的RGB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
public static uint GetColor(double value) { int r, g, b; int Rg = 0; //0 Green int Ry = 255, Gy = 255; //0.4 Yellow int Go = 165; //0.8 Orange int Gr = 0; //1 Red if (value >= 0 && value < 0.4) { r = GetRGB(value, 0, Ry, Rg, 0.4); g = 255; b = 0; } else if (value >= 0.4 && value < 0.8) { r = 255; g = GetRGB(value, 0.4, Go, Gy, 0.4); b = 0; } else { r = 255; g = GetRGB(value, 0.8, Gr, Go, 0.2); b = 0; } Color c = Color.FromArgb(r, g, b); int colorInt = GetRGBFomColor(c); uint i = uint.Parse(colorInt.ToString()); return i; } public static int GetRGBFomColor(Color color) { return (int)(((int)color.B << 16) | (ushort)(((ushort)color.G << 8) | color.R)); } |
绘制渐变图形和指针
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
TeeChart.IColorGridSeries c0 = axTChart1.Series(0).asColorGrid; for (int i = 0; i < 100; i++) { for (int j = 0; j < 2; j++) { uint u = Graham.GetColor1((float)i / 100); //制造预警值 c0.AddXYZ(i, 0, 5 + j, null, u); //渐变色 } } uint ui = Graham.GetColors(255, 0, 0); axTChart1.Series(1).AddXY(40, 5, null, ui); axTChart1.Series(1).AddXY(40, 7, null, ui);//绘制曲线 TeeChart.IBubbleSeries c2 = axTChart1.Series(2).asBubble; c2.AddBubble(40, 7.5, 0.5, "", ui);//绘制三角 |
到此,就可以生成开头图片中的效果,可能现在看起来还有点单调,有兴趣的朋友可以再丰富一下。
微信支付宝
如果本文帮助到您,请随意打赏作者