首页 > 编程知识 正文

javaawtFontcreateFont 画的时候字体不显示问题,打印的时候不显示表格

时间:2023-05-03 06:26:35 阅读:212775 作者:3602

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

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

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。