Java Write Text Image with Specific Fonts

删除回忆录丶 提交于 2019-12-08 04:05:40

问题


I'm writing some text on top of an existing image and the font isn't very sharp. Is there some settings either with the Graphics2D or Font classes that help make fonts look nicer when writing text on top of images? The Dante font doesn't come out as Dante when I write it. I've tried to use antialiasing but it had no effect (see setRenderingHint). The images came out the same with or without the RenderingHint set. Any suggestions?

public class ImageCreator{

public void createImage(String text){
     Graphics2D g = img.createGraphics(); //img is a BufferedImage read in from file system
     g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);
     Font fnt=new Font("Dante",1,20);
     Color fntC = new Color(4, 4, 109);       
     g.setColor(fntC);
     g.setFont(fnt);
     Dimension d = new Dimension(200, 113);
     drawCenteredString(text, d.width, d.height, g);
}
public static void drawCenteredString(String s, int w, int h, Graphics g) {
      FontMetrics fm = g.getFontMetrics();
      int x = (w - fm.stringWidth(s)) / 2;
      int y = (fm.getAscent() + (h - (fm.getAscent() + fm.getDescent())) / 2);
      g.drawString(s, x, y);
}

}  

回答1:


Use TextLayout, as shown here.

Addendum: The advantage of TextLayout is that RenderingHints may be applied to the FontRenderContext.



来源:https://stackoverflow.com/questions/5878517/java-write-text-image-with-specific-fonts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!