开发者

Java Write Text Image with Specific Fonts

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.h开发者_运维百科eight, 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);
}

}  


Use TextLayout, as shown here.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜