Swing文本看起来很糟糕

时间:2012-07-14 18:21:28

标签: java swing fonts antialiasing

我重写了JCOmponent的paintComponent()方法并在窗口中绘制文本。我在Ubuntu上运行并使用字体“Ubuntu Mono”(Ubuntu文本编辑器的默认字体)。当我的Java应用程序显示文本时,它看起来很懦弱和模糊。我做错了什么?

我正在画这样的文字:

graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
Font font = new Font("Ubuntu Mono", Font.PLAIN, 18);
fontMetrics = graphics.getFontMetrics(font);
graphics.setFont(font);
graphics.drawString(value, getX(), getY() + fontMetrics.getHeight());

在我的java应用程序中,它看起来像这样:

Java app text

在Ubuntu TextEditor中,它看起来像这样:

enter image description here

修改:如果使用.png张图片代替drawText(),效果会受损吗?这是一个商业应用程序,而不是需要流畅动画的游戏。

编辑:我改变颜色以匹配TextEditor的颜色,这实际上对质量有所帮助,但角色仍然更薄......你几乎看不到“。”。在gimp中,我可以通过创建带有抗锯齿的正确字体的文本来重新创建TextEditor外观。

4 个答案:

答案 0 :(得分:2)

读取.png图像并将其缓存到BufferedImage。性能不会受到影响 - 实际上使用这样的中间图像比首先绘制文本具有更好的性能。

确保将其设为兼容图像:

private Image getCompatibleImage(BufferedImage img) throws IOException {
        GraphicsConfiguration c = GraphicsEnvironment
                .getLocalGraphicsEnvironment().getDefaultScreenDevice()
                .getDefaultConfiguration();

        if (c.getColorModel().equals(img.getColorModel()))
            return img;

        BufferedImage compatible = c.createCompatibleImage(img.getWidth(),
                img.getHeight());
        Graphics cg = compatible.getGraphics();
        cg.drawImage(img, 0, 0, null);
        cg.dispose();

        return compatible;
    }

这样可以节省某些显示器上的每像素转换,从而提高性能。

答案 1 :(得分:2)

奇怪的是,我尝试使用“Monospaced”代替“Ubuntu Mono”:

graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

对我来说它看起来不错。这就是我将要使用的。

答案 2 :(得分:1)

你不一定做错什么。来自RenderingHints的API(强调我的):

这些键和值是提示,不要求给定的实现支持下面指出的所有可能的选择,或者它可以响应修改其算法选择的请求。各种值提示密钥也可以交互,使得在一种情况下支持给定密钥的所有变体,但是当修改与其他密钥相关联的值时,可以更加限制实现。 [剪断]

实现可以完全忽略提示,但应尽量使用尽可能接近请求的实现算法。

答案 3 :(得分:1)

尝试使用字体的本机桌面设置,而不是强制渲染提示,即:

Toolkit tk = Toolkit.getDefaultToolkit();
Map desktopHints = (Map)(tk.getDesktopProperty("awt.font.desktophints"));

...

if (desktopHints != null) {
    graphics.addRenderingHints(desktopHints);
}

source - Filthy Rich Clients

编辑:

请务必尝试各种提示,以控制文本呈现质量。这是referenceexamples