Java如何绘制一个圆角的进度条

原始需求是需要在导出的word中放入一个进度条,一开始就想直接贴图片,就想试一试如何直接画出来一个进度条,如下图所示:

 画图左圆角右方的画图比较难处理,因此采用截图的办法,先画一个完整的进度条,再截取到另外一张图片上合成的办法生成,步骤如下

先画一个完整的进度条:

        int width = 400; // 进度条宽度
        int height = 40; // 进度条高度
        int progress = 30; // 进度百分比
        var color1 = new Color(41, 164, 250); //进度条颜色
        var color2 = new Color(228, 228, 228); // 进度条背景色

        // 创建图像缓冲区 背景透明
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TRANSLUCENT);
        Graphics2D g = image.createGraphics();

        g.setColor(color1);
        g.fillRoundRect(0, 0, width, height, height, height);

结果如图:

 按照百分比截取,绘制到第二个图上:

        // 计算进度条长度
        int length = (int) ((progress / 100d) * width);

        // 创建图像缓冲区
        BufferedImage image2 = new BufferedImage(width, height, BufferedImage.TRANSLUCENT);
        Graphics2D g2 = image2.createGraphics();
        // 绘制背景
        g2.setColor(color2);
        g2.fillRoundRect(0, 0, width, height, height, height);
        // 截取图片
        g2.drawImage(image, 0, 0, length, height, 0, 0, length, height, null);

结果如图:

 完整代码如下:

package test.backend;

import org.junit.jupiter.api.Test;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;

public class ImageTest {

@Test
public void processTest() {
int width = 400; // 进度条宽度
int height = 40; // 进度条高度
int progress = 30; // 进度百分比
var color1 = new Color(41, 164, 250); //进度条颜色
var color2 = new Color(228, 228, 228); // 进度条背景色

// 创建图像缓冲区 背景透明
BufferedImage image = new BufferedImage(width, height, BufferedImage.TRANSLUCENT);
Graphics2D g = image.createGraphics();

g.setColor(color1);
g.fillRoundRect(0, 0, width, height, height, height);


// 计算进度条长度
int length = (int) ((progress / 100d) * width);

// 创建图像缓冲区
BufferedImage image2 = new BufferedImage(width, height, BufferedImage.TRANSLUCENT);
Graphics2D g2 = image2.createGraphics();
// 绘制背景
g2.setColor(color2);
g2.fillRoundRect(0, 0, width, height, height, height);
// 截取图片
g2.drawImage(image, 0, 0, length, height, 0, 0, length, height, null);

try {
File output1 = new File("progressbar1.png");
ImageIO.write(image, "png", output1);

File output2 = new File("progressbar.png");
ImageIO.write(image2, "png", output2);
} catch (Exception e) {
e.printStackTrace();
} finally {
g.dispose();
g2.dispose();

}
}
}

 

posted @ 2023-12-05 12:02  阿弥陀佛呵呵哒  阅读(101)  评论(0)    收藏  举报