4

当我尝试制作圆角矩形时,我的角变得非常像素化。有什么办法可以消除它们吗?

这是一张图片(注意角落):

在此处输入图像描述

这是我子类化并覆盖绘制方法的 Button 的代码(带有像素化角的那个):

public class ControlButton extends JButton {

    public final static Color BUTTON_TOP_GRADIENT = new Color(176, 176, 176);
    public final static Color BUTTON_BOTTOM_GRADIENT = new Color(156, 156, 156);

    public ControlButton(String text) {
        setText(text);
    }

    public ControlButton() {
    }

    @Override
    protected void paintComponent(Graphics g){
        Graphics2D g2 = (Graphics2D)g.create();
        g2.setPaint(new GradientPaint(
                new Point(0, 0), 
                BUTTON_TOP_GRADIENT, 
                new Point(0, getHeight()), 
                BUTTON_BOTTOM_GRADIENT));
        g2.fillRoundRect(0, 0, getWidth(), getHeight(), 20, 20);
        g2.dispose();
    }
}
4

2 回答 2

9

试试这个:

RenderingHints qualityHints = new RenderingHints(
  RenderingHints.KEY_ANTIALIASING,
  RenderingHints.VALUE_ANTIALIAS_ON );
qualityHints.put(
  RenderingHints.KEY_RENDERING,
  RenderingHints.VALUE_RENDER_QUALITY );
g2.setRenderingHints( qualityHints );

看一下文档:

代码:

import javax.swing.*;

import java.awt.*;

public class ControlButton extends JButton {

  public final static Color BUTTON_TOP_GRADIENT = new Color(176, 176, 176);
  public final static Color BUTTON_BOTTOM_GRADIENT = new Color(156, 156, 156);

  public ControlButton(String text) {
    setText(text);
  }

  public ControlButton() {
  }

  @Override
  protected void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D)g.create();
    RenderingHints qualityHints =
      new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    qualityHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g2.setRenderingHints(qualityHints);

    g2.setPaint(new GradientPaint(new Point(0, 0), BUTTON_TOP_GRADIENT, new Point(0, getHeight()),
                                  BUTTON_BOTTOM_GRADIENT));
    g2.fillRoundRect(0, 0, getWidth(), getHeight(), 20, 20);
    g2.dispose();
  }

  public static void main(String args[]) {
    JFrame frame = new JFrame("test");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(new ControlButton("Hello, World"));
    frame.pack();
    frame.setVisible(true);
  }
}
于 2013-05-31T18:40:56.037 回答
0

我这样做了:

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

我觉得它比 Dave Jarvis 的方法给了我更平滑的边缘,但我可能是错的。

于 2020-03-08T05:18:18.410 回答