画线条
int width = 500;
int height = 300;
BufferedImage outImage = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR_PRE);
Graphics2D card = outImage.createGraphics();
card.setStroke(new BasicStroke(1));
card.drawLine(0, 0, width, 0);
card.drawLine(0, 0, 0, height);
card.drawLine(0, height - 1, width - 1, height - 1);
card.drawLine(width - 1, 0, width - 1, height - 1);
- (x1,y1)与(x2,y2)实际为两个点,所画的线条就是两个点的连线
写文本
card.setFont(new Font("微软雅黑", Font.BOLD, 14));
card.setPaint(Color.RED);
card.drawString("我是红色微软雅黑大小为14的加粗字体", 20, 20);
card.setFont(new Font("宋体", Font.PLAIN, 17));
card.setPaint(Color.BLACK);
card.drawString("我是黑色宋体大小为17的字体", 20, 50);
写可设置字体间距的文本
public static void myDrawString(String str, int x, int y, double rate, Graphics g) {
String tempStr;
int orgStringWight = g.getFontMetrics().stringWidth(str);
int orgStringLength = str.length();
int tempx = x;
int tempy = y;
while (str.length() > 0) {
tempStr = str.substring(0, 1);
str = str.substring(1);
g.drawString(tempStr, tempx, tempy);
tempx = (int) (tempx + (double) orgStringWight / (double) orgStringLength * rate);
}
}
添加图片
BufferedImage img = ImageIO.read(this.getClass().getResourceAsStream(logoPath));
card.drawImage(img.getScaledInstance(64, 18, Image.SCALE_DEFAULT), 31, 23, null);
剪切图片
card.setClip(new RoundRectangle2D.Double(0, 0, width, height, 0, 0));
card.dispose();
outImage.flush();
消除抗锯齿
card.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
导出图片
BufferedImage image = outImage;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.flush();
ImageIO.write(image, "png", baos);
BufferedImage newBufferedImage = new BufferedImage(
width, height,
BufferedImage.TYPE_INT_RGB);
newBufferedImage.createGraphics().drawImage(image, 0, 0, Color.WHITE, null);
ImageIO.write(newBufferedImage, "png",
new File(fileName));
baos.close();
image.flush();
} catch (IOException e) {
e.printStackTrace();
}