java.awt.Font.createFont 画图的时候字体不显示问题

由于不想在服务器去安装字体 想通过项目里放置字体文件来防止项目上线字体问题导致画出来的图中文乱码,所以决定使用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,
                              IOException

Returns a new Font using the specified font type and input data. The new Font is created with a point size of 1 and style PLAIN. This base font can then be used with the deriveFont methods in this class to derive new Font objects with varying sizes, styles, transforms and font features. This method does not close the InputStream.

To make the Font available to Font constructors the returned Font must be registered in the GraphicsEnviroment by calling registerFont(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的字体

好了 问题解决  还是要多看官方文档啊

  • 12
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值