I'm using an 4K display here with 175% scaling and Windows 11. I have a Java application that writes text to a bitmap and displays this bitmap. The text quality is fine and very smooth with an Java 1.8.0_371. And all OpenJDK versions I've tried all produce a poorer and pixelated output as you can see in the images:
Is there a way to improve the quality of the text?
Sourcecode is:
package 4ktest;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
public class TestWindow1 extends JPanel {
private BufferedImage image;
public TestWindow1(String text) {
image = new BufferedImage(600, 100, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = image.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, image.getWidth(), image.getHeight());
g2d.setColor(Color.BLACK);
g2d.setFont(new Font("Times New Roman", Font.PLAIN, 50));
g2d.drawString(text, 10, 50);
g2d.dispose();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Text to Bitmap");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 150);
TestWindow1 panel = new TestWindow1("Version " + System.getProperty("java.version") );
frame.add(panel);
frame.setVisible(true);
});
}
}
I could reproduce the problem, and I was able to fix the problem by using rendering hints in the paintComponent method.
public static void highQualityRenderingHints(Graphics2D g2d){
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
}
Calling that method on the Graphics
provided in the paintComponent method.
I checked and the only hint that was needed to show the improvement wasRenderingHints.KEY_RENDERING