drawstring 文本居中_Graphics2D 绘制文字,不能稳定居中

以下是使用 Graphics2D 绘制图片的方法,在使用过程中,单笔调用都是居中。

但是如果换成批量调用,在生成部分图片中会出现部分行的文字不能正常居中的情况。

public static BufferedImage writeTextCenter(BufferedImage inputImage, int y, String text, Font font, Color color) throws IOException, FontFormatException {

Assert.notNull(inputImage, "input image is null");

Graphics2D graphics2d = inputImage.createGraphics();

graphics2d.setFont(font);

graphics2d.setColor(color);

graphics2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

FontMetrics fontMetrics = graphics2d.getFontMetrics(font);

// 计算出中心点 x 位置

int centerX = inputImage.getWidth() / 2;

// 文字宽度

int textWidth = fontMetrics.stringWidth(text);

logger.info("centerX = [" + centerX + "], textWidth = [" + textWidth + "], text = [" + text + "]");

// 计算出中心点,并且绘制出文字

graphics2d.drawString(text, centerX - textWidth / 2, y);

graphics2d.dispose();

return inputImage;

}

要在Graphics2D中使文本居中,可以使用以下步骤: 1. 获取字体的宽度和高度: ``` FontMetrics fontMetrics = g2d.getFontMetrics(font); int stringWidth = fontMetrics.stringWidth(text); int stringHeight = fontMetrics.getAscent() - fontMetrics.getDescent(); ``` 2. 计算文本的中心点: ``` int centerX = (int) (getWidth() / 2 - stringWidth / 2); int centerY = (int) (getHeight() / 2 + stringHeight / 2); ``` 3. 在中心点绘制文本: ``` g2d.drawString(text, centerX, centerY); ``` 完整的示例代码如下: ```java public class CenteredText extends JPanel { private Font font = new Font("Arial", Font.PLAIN, 24); private String text = "Hello, world!"; @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; // 获取字体的宽度和高度 FontMetrics fontMetrics = g2d.getFontMetrics(font); int stringWidth = fontMetrics.stringWidth(text); int stringHeight = fontMetrics.getAscent() - fontMetrics.getDescent(); // 计算文本的中心点 int centerX = (int) (getWidth() / 2 - stringWidth / 2); int centerY = (int) (getHeight() / 2 + stringHeight / 2); // 在中心点绘制文本 g2d.setFont(font); g2d.drawString(text, centerX, centerY); } public static void main(String[] args) { JFrame frame = new JFrame("Centered Text"); frame.add(new CenteredText()); frame.setSize(400, 300); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值