Java 用特定字体写入文本图像

标签 java graphics graphics2d antialiasing

我正在现有图像上写一些文本,但字体不是很清晰。在 Graphics2D 或 Font 类中是否有一些设置可以帮助在图像上书写文本时使字体看起来更好?当我编写 Dante 字体时,它不会显示为 Dante。我尝试过使用抗锯齿功能,但没有效果(请参阅 setRenderingHint)。无论是否设置 RenderingHint,图像的结果都是一样的。有什么建议么?

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);
}

}  

最佳答案

使用TextLayout ,如图here .

附录: TextLayout 的优势是 RenderingHints 可以应用于 FontRenderContext

关于Java 用特定字体写入文本图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5878517/

相关文章:

java - 使用 Action.SEND 从另一个应用程序接收隐式 Intent 时显示错误的 Activity

java - 坐标网格中球的真实反弹(离线)

java - 如何通过快速拖动鼠标光标绘制重复椭圆的连续曲线?

java - 使用 arrayList 作为 Graphics2d 中的 y 坐标

java - 在 Talend 5.5 中使用正则表达式的 jsonpath

java - 使用 java EWS API 从 Exchange 检索邮件配额?

java - 将图像分配给字符串

matrix - 剪切矩阵作为基本变换的组合?

java - Java中数据和文本的旋转坐标平面

java - 根据两个旋转器更改图像