JDK8升级到JDK17 sun.font.FontDesignMetrics类无效替代方案
问题:
项目从jdk1.8切成jdk17后
FontMetrics fontMetrics = FontDesignMetrics.getMetrics(font);
报错: cannot access class sun.font.FontDesignMetrics (in module java.desktop) because module java.desktop does not export sun.font
搜索资料,最多的解决方案是参考
https://stackoverflow.com/questions/61771048/maven-run-and-build-with-add-exports
https://blog.csdn.net/u012448758/article/details/125689992
在pom文件中添加配置,详细可查看上述博客方法。但是这种方法我试了本地运行时不时就会报错,而且线上也是。原因未找到。
最后多方查找找到了可以替换FontDesignMetrics类来计算文本高度的方法。
FontRenderContext frc = new FontRenderContext(new AffineTransform(), true, true);
Font font = new Font("微软雅黑", Font.ITALIC, 28);
String wordContent = "你好啊!我的Friend";
Rectangle rec = font.getStringBounds(wordContent, frc).getBounds();
int height = rec.height;//计算高
int width = rec.width; //计算文字宽度
下面是在绘制图片文字的完整示例
public static void createWordPicture2(String wordContent,File watermarkUrl) throws IOException {
Font font = new Font("微软雅黑", Font.ITALIC, 28);
//FontDesignMetrics metrics = FontDesignMetrics.getMetrics(font);
FontRenderContext frc = new FontRenderContext(new AffineTransform(), true, true);
//int width = getWordWidth(font, wordContent);//计算宽
Rectangle rec = font.getStringBounds(wordContent, frc).getBounds();
int height = rec.height;//计算高
int width = rec.width; //计算文字宽度
BufferedImage bufferedImage = ImageIO.read(watermarkUrl);
Graphics2D graphics = (Graphics2D)bufferedImage.getGraphics();
graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
//设置背影颜色
graphics.setColor(Color.red);
GradientPaint paint = new GradientPaint(0, 0, Color.PINK, (width+100)/2,0, Color.RED, true);
graphics.setPaint(paint);// 设置渐变
graphics.fillRect(0, 0, width+100, height);
graphics.setFont(font);
graphics.setColor(Color.WHITE);
graphics.drawString(wordContent, 50+100,- rec.y );//图片上写文字
graphics.dispose();
write(bufferedImage, watermarkUrl.getPath());
}
public static void write(BufferedImage bufferedImage, String target) throws IOException {
File file = new File(target);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
try (OutputStream os = new FileOutputStream(target)) {
ImageIO.write(bufferedImage, "JPG", os);
}
}
原文地址:https://blog.csdn.net/yusewuhen/article/details/140431220
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!