Anti-aliasing in paintComponent() method

◇◆丶佛笑我妖孽 提交于 2019-12-30 07:23:11

问题


I want to print some text using the paintComponent(..) method.

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

But the text is somewhat jaggy. How could you force text drawing with [anti-aliasing] in this method?

Thank you.


回答1:


You can set double buffering by:

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

or simply call JComponent#setDoubleBuffered(..).

You can also set RenderingHints for Graphics2D objects like anti-aliasing and text anti-aliasing to improve Swing painting quality by:

  @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);
}


来源:https://stackoverflow.com/questions/13236797/anti-aliasing-in-paintcomponent-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!