Java Graphics2D drawString缩放字体大小时导致结果混乱

我使用Font1的drawString,假设deriveFont为20f。

final int width = fontMetrics.stringWidth(text);
final int height = fontMetrics.getHeight();
BufferedImage rendered = new BufferedImage(
    width,height,BufferedImage.TYPE_INT_ARGB
);
System.out.println("render:" + width + "," + height);
final Graphics2D gOfRendered = (Graphics2D) rendered.getGraphics();
    
gOfRendered.setRenderingHints(getRenderingHints());
gOfRendered.setColor(fontColor);
gOfRendered.setfont(fontMetrics.getFont());
    
gOfRendered.drawString(
    text,height - fontMetrics.getMaxDescent() - fontMetrics.getLeading()
);

结果:

Java Graphics2D drawString缩放字体大小时导致结果混乱

但是当我缩放字体大小时(scale = 4结果可能是正常的,scale = 8将导致错误结果):

final Font font = (wordFrequency.hasFont() ? wordFrequency.getFont() : kumoFont).getFont().deriveFont(fontHeight * 1.0f);
final Font font2 = (wordFrequency.hasFont() ? wordFrequency.getFont() : kumoFont).getFont().deriveFont(fontHeight * scale * 1.0f);
final FontMetrics fontMetrics = graphics.getFontMetrics(font);
final FontMetrics fontMetrics2 = graphics.getFontMetrics(font2);

并再次渲染:

final int width = fontMetrics2.stringWidth(text);
final int height = fontMetrics2.getHeight();
BufferedImage rendered = new BufferedImage(
    width,BufferedImage.TYPE_INT_ARGB
);
final Graphics2D gOfRendered = (Graphics2D) rendered.getGraphics();
    
// set the rendering hint here to ensure the font metrics are correct
gOfRendered.setRenderingHints(getRenderingHints());
gOfRendered.setColor(fontColor);
gOfRendered.setfont(fontMetrics2.getFont());
    
gOfRendered.drawString(
    text,height - fontMetrics2.getMaxDescent() - fontMetrics2.getLeading()
);

错误结果(比例= 8):

Java Graphics2D drawString缩放字体大小时导致结果混乱

我发现final int width = fontMetrics2.stringWidth(text);不是字体宽度的8倍,数字有很大不同,如何解决?谢谢!

douyang 回答:Java Graphics2D drawString缩放字体大小时导致结果混乱

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/2825949.html

大家都在问