【问题标题】:Problems with rendering strings on BufferedImage在 BufferedImage 上渲染字符串的问题
【发布时间】:2015-03-20 02:21:53
【问题描述】:

这是我在这里的第一个主题,我为我的英语不好(我是意大利人)向你道歉。

我使用 javax.swing 库编写了一个示例 2d 应用程序。

我使用BufferedImage 渲染形状、图像和字体。 图像在 Canvas (java.awt) 中呈现。

图片尺寸为 100x100,Canvas 尺寸为 700x500。

现在的问题是当我将字符串绘制到图像中时,因为字符串是像素化的。我尝试激活抗锯齿,但它们看起来很模糊。

有没有办法解决这个问题?

这是我的代码:

public class Application extends Canvas implements Runnable {
public static final int WIDTH=700, HEIGHT=500;

private BufferedImage image;
private Thread thread;

public Application() {
    image=new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);

    setSize(WIDTH, HEIGHT);
}

public void addNotify() {
    super.addNotify();
    if(thread==null) {
        thread=new Thread(this);
    }
    thread.start();
}
public void run() {
    while(true) {
        render();
    }
}

public void render() {
    BufferStrategy bs=getBufferStrategy();
    if(bs==null) {
        createBufferStrategy(2);
        return;
    }

    Graphics2D g=(Graphics2D)bs.getDrawGraphics();

    Graphics2D imageG=(Graphics2D)image.createGraphics();
    image.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    imageG.setColor(Color.BLUE);
    imageG.fillRect(0, 0, image.getWidth(), image.getHeight());

    //rendering other stuffs

    imageG.setColor(Color.WHITE);

    Font f=new Font(Font.SANS_SERIF, Font.PLAIN, 15);
    imageG.setFont(f);
    imageG.drawString("hello", 40, 50);


    g.drawImage(image, 0, 0, WIDTH, HEIGHT, null);

    g.dispose();
    bs.show();
}

public static void main(String[] args) {
    JFrame f=new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);



    f.add(new Application());
    f.pack();
    f.setLocationRelativeTo(null);
    f.setVisible(true);
}
}

【问题讨论】:

  • “我尝试激活抗锯齿功能..” 我在该代码中没有看到它尝试过的任何地方..
  • 尝试this code中看到的各种选项组合。
  • 还有这个相关的example
  • 我添加了关于抗锯齿的代码行。我删除了它,因为它不起作用。
  • 我阅读了这些示例,但不是我的情况。也许 BufferedImage 从 100x100 调整到 700x500 是问题所在。我想增加 BufferedImage 的大小。是这样吗?

标签: java string swing graphics2d


【解决方案1】:

1:文本的抗锯齿是KEY_TEXT_ANTIALIASING

2:您正在将图像拉伸到文本变得非常像素化的位置。要么使您的图像更大,使您的字体更大,或者不要用图像填充画布(仅绘制它的一部分),而是为画布着色。 - 看看drawImage(...)

【讨论】:

    猜你喜欢
    • 2018-07-27
    • 2017-08-17
    • 2016-03-10
    • 1970-01-01
    • 2013-02-28
    • 1970-01-01
    • 2012-11-08
    • 2013-04-03
    • 2014-08-09
    相关资源
    最近更新 更多