如何提高图形的 drawString 方法的字体质量?

How to increase font quality on drawString method of Graphics?

在 Paint XP 或 Paint Windows8 中,当您书写文本时,程序会自动提高字体质量(至少对于财务打印机而言)。我想知道如何使用下面相同的 Java 代码执行此操作。

首先,看这张图片明白我的意思:

Text Quality Example

BufferedImage image = ImageIO.read(new File("blankdocument.bmp"));
Graphics g = ((BufferedImage) image).getGraphics();

Font helvetica = new Font("Lucida Sans Unicode", Font.PLAIN, 13);
g.setColor(Color.black);
g.setFont(helvetica);

g.drawString("TEXT WRITING EXAMPLE.", 5, 10);
ImageIO.write(image, "PNG", new File("testx.PNG"));
image.flush();

您可以打开抗锯齿功能。来自 Controlling Rendering Quality

To set or change the rendering hints attribute in the Graphics2D context, construct a RenderingHints object and pass it into Graphics2D by using the setRenderingHints method. If you just want to set one hint, you can call Graphics2D setRenderingHint and specify the key-value pair for the hint you want to set. (The key-value pairs are defined in the RenderingHints class.)

Graphics2D g2 = (Graphics2D) g;
RenderingHints rh = new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING,
            RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2.setRenderingHints(rh);

您应该打开 Anti-aliasing。 java 中的抗锯齿可以像这样启用:

// this is the same as getGraphics() but returns a Graphics2D instead.
Graphics2D g2 = image.createGraphics();

RenderingHints rh = new RenderingHints(
    RenderingHints.KEY_TEXT_ANTIALIASING,
    RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2.setRenderingHints(rh);