簡體   English   中英

java中圖像的平滑縮放

[英]Smooth Scaling of Image in java

我創建了一個擴展 Jbutton 的按鈕,我添加到按鈕圖像中,但這不會使圖像平滑。 我嘗試getScaledInstance但它不起作用

這是原圖:

這是原圖

這就是它真正呈現圖片的方式:

在此處輸入圖片說明

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

我運行代碼,有時它會向我顯示圖片,有時它會向我顯示空方塊 這向我顯示了控制台中的錯誤。

只有我用鼠標移動它們才會出現圖片

在此處輸入圖片說明

請嘗試以下操作。 這是不言自明的。

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



我不明白為什么需要這么復雜。
我建議簡單地創建一個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大小與圖標大小相同,因為您暗示這是您在對另一個答案的評論中想要的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM