Java GradientPaint 画多段颜色的colorbar(颜色条或渐变色条)

主要运用的Java基础的awt画图包,方便的画出来colorbar,如下图所示。
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可以更自由的画出不同形状的渐变颜色块,所以只要根据需求选择合适的即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值