Java用BufferedImage和Graphics画图。

问题:网上大部分内容重复,且描述简单。注:内容:将某个字生成图片,且对图片背景色和图片上字的颜色有要求的情况。

解决:先用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();

文章来自:http://www.cnblogs.com/--yz/p/4551537.html
© 2021 jiaocheng.bubufx.com  联系我们
ICP备案:鲁ICP备09046678号-3