主要运用的Java基础的awt画图包,方便的画出来colorbar,如下图所示。
这个colorbar用了四种颜色:红色、黄色、浅蓝、深蓝。下面展示了两种方法:
- GradientPatint
public BufferedImage drawGradient1(int width, int height) {
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // 创建一个图像(jpg)
Graphics2D g2 = (Graphics2D) img.getGraphics();
Color midColor = new Color(0, 210, 231); // 浅蓝色
// 运用GradientPatint类来实现渐变
// 因为有多段渐变,所以分别把多个GradientPatint连续画出来
GradientPaint grad = new GradientPaint(0, 0, Color.red, 0, height/3, Color.yellow); // 起始点,起始颜色,终点,终点颜色
g2.setPaint(grad); // 选择好渐变颜色
g2.fillRect(0, 0, width, height/3); // 用这个颜色画长方形(起始点,终点)
GradientPaint grad2 = new GradientPaint(0, height/3, Color.yellow, 0, height/3 * 2, midColor);
g2.setPaint(grad2);
g2.fillRect(0, height/3, width, height/3);
GradientPaint grad3 = new GradientPaint(0, height/3 * 2, midColor, 0, height, Color.blue);
g2.setPaint(grad3);
g2.fillRect(0, height/3 * 2, width, height - height/3 * 2);
g2.dispose();
return img;
}
- LinearGradientPatint
public BufferedImage drawGradient2(int width, int height) {
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // 创建一个图像(jpg)
Graphics2D g2 = (Graphics2D) img.getGraphics();
Color midColor = new Color(0, 210, 231); // 浅蓝色
// 运用LinearGradientPatint类来直接实现多段渐变
float[] portions = new float[] {0f, 0.33f, 0.66f, 1f}; // 每段的起始位置在总长的比例(必须要递增)
Color[] colors = new Color[] {Color.red, Color.yellow, midColor, Color.blue}; // 每段对应的颜色
LinearGradientPaint linearGradientPaint = new LinearGradientPaint(0, 0, 0, height, portions, colors); // 起始点,终点,比例,颜色
g2.setPaint(linearGradientPaint); // 选择好渐变颜色
g2.fillRect(0, 0, width, height); // 用这个颜色画长方形(起始点,终点)
g2.dispose();
return img;
}
如果是画一个长方形的colorbar,可以直接使用LinearGradientPaint一步画出来,但多段不同的GradientPaint可以更自由的画出不同形状的渐变颜色块,所以只要根据需求选择合适的即可。