由于不想在服务器去安装字体 想通过项目里放置字体文件来防止项目上线字体问题导致画出来的图中文乱码,所以决定使用Font.createFont(int fontFormat, InputStream fontStream)来导入本地字体。
首先我是这样写的
//模板图片
ClassPathResource resource = new ClassPathResource("template/template1.png");
//字体文件
ClassPathResource fontResource = new ClassPathResource("font/simsun.ttf");
// 获取模板图片
BufferedImage buffImg = ImageIO.read(resource.getInputStream());
// 开启画图
Graphics2D graphics = buffImg.createGraphics();
Font qrNameFont = Font.createFont(Font.TRUETYPE_FONT, fontResource.getInputStream());
graphics.setFont(qrNameFont);
//接下来就是操作graphics画图 但是字总写不出来
一番抓耳挠腮之后。度娘了半天的我决定看官方文档
public static Font createFont(int fontFormat, InputStream fontStream) throws FontFormatException, IOExceptionReturns a new
Font
using the specified font type and input data. The newFont
is created with a point size of 1 and stylePLAIN
. This base font can then be used with thederiveFont
methods in this class to derive newFont
objects with varying sizes, styles, transforms and font features. This method does not close theInputStream
.To make the
Font
available to Font constructors the returnedFont
must be registered in theGraphicsEnviroment
by callingregisterFont(Font)
.
为了让字体可用必须注册。。。。。。。原因找到了,接下来看GraphicsEnviroment
的registerFont
方法
可以看到整个GraphicsEnviroment
中有创建 GraphicsEnviroment
对象的getLocalGraphicsEnvironment()方法
还有一个创建Graphics2D对象的createGraphics(java.awt.image.BufferedImage)方法。
好了 流程大概就清楚了
首先创建GraphicsEnviroment
对象 再把创建的字体registerFont进GraphicsEnviroment
对象 最终通过GraphicsEnviroment创建
Graphics2D对象 用这个Graphics2D对象才有创建的字体
代码改写如下
//模板
ClassPathResource resource = new ClassPathResource("template/template1.png");
//字体
ClassPathResource fontResource = new ClassPathResource("font/simsun.ttf");
// 获取模板图片
BufferedImage buffImg = ImageIO.read(resource.getInputStream());
// 设置文字
Font font = Font.createFont(Font.TRUETYPE_FONT, fontResource.getInputStream());
设置字体
font = font.deriveFont(Font.BOLD, 64F);
Font multiFont = font.deriveFont(Font.BOLD, 60f);
Font finalfont = font.deriveFont(Font.PLAIN, 50f);
GraphicsEnvironment localGraphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();
localGraphicsEnvironment.registerFont(font);
localGraphicsEnvironment.registerFont(multiFont);
localGraphicsEnvironment.registerFont(finalfont);
// 开启画图
Graphics2D graphics = localGraphicsEnvironment.createGraphics(buffImg);
//设置字体
graphics.setFont(font);
//这里就是大小为64F的字体
graphics.setFont(multiFont);
//这里就是大小为60f的字体
graphics.setFont(finalfont);
//这里就是大小为50f的字体
好了 问题解决 还是要多看官方文档啊