(1)加载自定义的ttf字体
import java.awt.Font;
Font demiFont = Font.createFont(Font.TRUETYPE_FONT, new File("字体的路径"));
(2)加载图片模板
import java.awt.Graphics2D;
File typeAFile = new File(“模板图片的路径”);
BufferedImage bgImage = ImageIO.read(typeAFile);
(3)获得Graphics2D
Graphics2D graphics2D = bgImage.createGraphics();
AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER);
graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
graphics2D.setComposite(ac);
graphics2D.setBackground(Color.WHITE);
// 画图片
graphics2D.drawImage(BufferedImage codeImage, x, y, width, height, null);
// 创建指定大小的字体
Font accountHolderNameFont= demiFont.deriveFont(Font.BOLD, 80);
graphics2D.setFont(accountHolderNameFont);
graphics2D.setColor(new Color(109, 110, 112));
graphics2D.drawString("要画字符串",x,y);
//下面是一个很重要的方法,可以获取指定字体大小的字符串的像素宽度
import sun.font.FontDesignMetrics;
FontDesignMetrics.getMetrics(accountHolderNameFont).stringWidth(“字符串”));