Java用BufferedImage和Graphics画图

来源:互联网 发布:eplan软件安装 编辑:程序博客网 时间:2024/05/14 10:57

解决:先用Graphics的方法setColor设置一下颜色,然后再用该类的fillRect填充背景色,接着再用该类的setColor设置一下颜色,再接着就是用该类的drawString画字了。ImageIO.write输出图片。最后用该类的dispose释放资源。

局部代码:

int imageWidth = 200;
int imageHeight = 200;
BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
Graphics graphics = image.getGraphics();
int fontSize = 100;
Font font = new Font("楷体", Font.PLAIN, fontSize);
graphics.setFont(font);
graphics.setColor(new Color(246, 96, 0));
graphics.fillRect(0, 0, imageWidth, imageHeight);
graphics.setColor(new Color(255, 255, 255));
int strWidth = graphics.getFontMetrics().stringWidth("好");
graphics.drawString("好", fontSize - (strWidth / 2), fontSize + 30);
ImageIO.write(image, "PNG", new File("D:\\abc.png"));
graphics.dispose();

0 0