Java中图像的平滑缩放

时间:2020-01-27 17:19:33

标签: java swing

我创建了一个扩展Jbutton的按钮,我将其添加到按钮图像中,但这不能使图像平滑。 我尝试getScaledInstance,但没用

这是原始图像:

This is the origianl image

这就是它真正呈现图片的方式:

enter image description here

public class Button extends JButton {
private Image image;


public Button(Image image) {
    this.image = image;
}

public Image getImage() {
    return image;
}

public void setImage(Image image) {
    this.image = image;
}

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
}

编辑:

我理解为什么它不能使图像平滑。 我不得不将drawImage更改为g.drawImage(image, 0, 0, null);

我运行代码,有时向我显示图片,有时向我显示空白方框,这向我显示了控制台中的错误。

只有我用鼠标移动它们,图片才会出现

enter image description here

2 个答案:

答案 0 :(得分:0)

尝试以下方法。这很自我解释。

public class CircleDisplay extends JPanel {

    final static int height = 500;
    final static int width = 500;
    Image img = null;
    JFrame frame = new JFrame();

    public static void main(String[] args) {
        new CircleDisplay();
    }

    public CircleDisplay() {
        Image img = null;
        try {
            img = ImageIO
                    .read(new File("f:yellowCircle.png"));
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        frame.setDefaultCloseOperation(
                JFrame.EXIT_ON_CLOSE);
        frame.add(this);
        img = 
                img.getScaledInstance(50, 50,
                        Image.SCALE_SMOOTH);
        Button b = new Button(img);
        b.setPreferredSize(new Dimension(50,50));

        add(b);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

class Button extends JButton {
    Image img;
    public Button(Image img) {
        this.img = img;
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        g.drawImage(img,0,0,null);
    }
}



答案 1 :(得分:0)

我不明白为什么它需要这么复杂。
我建议您简单地创建一个ImageIcon并设置JButton图标。
示例代码:

javax.swing.ImageIcon imgIco = new javax.swing.ImageIcon("path-to-icon-file");
javax.swing.JButton button2 = new javax.swing.JButton(imgIco);
button2.setPreferredSize(new java.awt.Dimension(imgIco.getIconWidth(), imgIco.getIconHeight()));

上面的代码的最后一行确保JButton的大小与图标的大小相同,因为您暗示这就是您想要在其他答案中添加注释的地方。