【问题标题】:Anti-aliasing in paintComponent() methodpaintComponent() 方法中的抗锯齿
【发布时间】:2012-10-25 13:34:33
【问题描述】:

我想使用paintComponent(..) 方法打印一些文本。

@Override
  protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.setColor(Color.red);
    g.drawString("Hello world", 10, 10);
}

但文字有些参差不齐。 在这种方法中如何强制使用 [anti-aliasing] 绘制文本?

谢谢。

【问题讨论】:

  • 你的意思是抗锯齿而不是双缓冲?

标签: java string swing graphics paintcomponent


【解决方案1】:

您可以通过以下方式设置双缓冲:

class MyPanel extends JPanel {
    public MyPanel() {
        super(true);//set Double buffering for JPanel
    }
}

或直接致电JComponent#setDoubleBuffered(..)

您还可以为Graphics2D 对象设置RenderingHints,例如anti-aliasing文本anti-aliasing,通过以下方式提高 Swing 绘画质量:

  @Override
  protected void paintComponent(Graphics g) {
    super.paintComponent(g); 
    Graphics2D graphics2D = (Graphics2D) g;

    //Set  anti-alias!
    graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON); 

   // Set anti-alias for text
    graphics2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
            RenderingHints.VALUE_TEXT_ANTIALIAS_ON); 

    graphics2D.setColor(Color.red);
    graphics2D.drawString("Hello world", 10, 10);
}

【讨论】:

  • 我认为您应该从答案中删除双缓冲部分以避免混淆。为此,有other questions
  • 在JPanel的构造函数中设置这个就足够了,还是我必须在每次调用paintComponent时设置这个策略?
猜你喜欢
  • 2014-02-18
  • 1970-01-01
  • 2010-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多