Java 使用Graphics2D图片上写字,计算宽和高 以及字体的位置 您所在的位置:网站首页 java设置字体类型 Java 使用Graphics2D图片上写字,计算宽和高 以及字体的位置

Java 使用Graphics2D图片上写字,计算宽和高 以及字体的位置

2023-07-23 12:04| 来源: 网络整理| 查看: 265

如上图,这个是一个有中文与英文的字符串。 中文与英文字符的宽高是不一样的,如果想要生成一张宽高刚的图片,这样我就需要计算每一个字符的宽度,及合适的高;

java.awt.FontMetrics 这个类对文字的宽高位置有详细的介绍;

计算使用字体的一段字符串的宽

public static int getWordWidth(Font font, String content) { FontDesignMetrics metrics = FontDesignMetrics.getMetrics(font); int width = 0; for (int i = 0; i < content.length(); i++) { width += metrics.charWidth(content.charAt(i)); } return width; }

计算使用字体的最大的高度

FontDesignMetrics metrics = FontDesignMetrics.getMetrics(font); int height = metrics.getHeight();

在图片是写文字时最合适的位置 

Ascent是从基线到顶部最大的高,也可以当做一个种字体画图时最有可以点用的高度

graphics.drawString(content, 0, metrics.getAscent());

测试代码

import sun.font.FontDesignMetrics; import javax.imageio.ImageIO; import java.awt.*; import java.awt.font.LineMetrics; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; /** * Created by zengrenyuan on 18/5/11. */ public class ImageTest { public static void main(String[] args) throws IOException { Font font = new Font("微软雅黑", Font.BOLD, 32); String content = "你好Java!"; FontDesignMetrics metrics = FontDesignMetrics.getMetrics(font); int width = getWordWidth(font, content);//计算图片的宽 int height = metrics.getHeight();//计算高 BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D graphics = bufferedImage.createGraphics(); graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER)); //设置背影为白色 graphics.setColor(Color.WHITE); graphics.fillRect(0, 0, bufferedImage.getWidth(), bufferedImage.getHeight()); graphics.setFont(font); graphics.setColor(Color.BLACK); graphics.drawString(content, 0, metrics.getAscent());//图片上写文字 graphics.dispose(); write(bufferedImage, "/data/test.png"); } public static int getWordWidth(Font font, String content) { FontDesignMetrics metrics = FontDesignMetrics.getMetrics(font); int width = 0; for (int i = 0; i < content.length(); i++) { width += metrics.charWidth(content.charAt(i)); } return width; } 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, "PNG", os); } } }

参考资料:http://tool.oschina.net/uploads/apidocs/jdk-zh/java/awt/FontMetrics.html



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有