簡體   English   中英

在JPanel中調整圖像大小並重新繪制圖像

[英]Resize and Redraw a image in a JPanel

我正在創建一個簡單的Java程序來加載圖像並放大/縮小圖像。 到目前為止,我已經能夠加載圖片並進行縮放。 但是當繪制縮小的圖像時,我仍然可以在JPanel上看到先前的圖像。

加載圖像的代碼

JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new FileNameExtensionFilter("Images(jpg,png,gif)", "jpg","png","gif"));
int opt = fileChooser.showOpenDialog(this);
if(opt  == JFileChooser.APPROVE_OPTION){
    String filePath = fileChooser.getSelectedFile().getAbsolutePath();
    try {
        bufImage = ImageIO.read(fileChooser.getSelectedFile());
    } catch (IOException ex) {
        Logger.getLogger(ImageZoom.class.getName()).log(Level.SEVERE, null, ex);
    }
    image = new ImageIcon(filePath);
    imgWidth = image.getIconWidth();
    imgHeight = image.getIconHeight();

    imagePanel.getGraphics().drawImage(image.getImage(), 0, 100, image.getIconWidth(), image.getIconHeight(), imagePanel);
}

放大代碼

double scale_factor = 1.5;
imagePanel.getGraphics().drawImage(image.getImage(), 0, 100, (int)(imgWidth*=scale_factor), (int)(imgHeight*=scale_factor), imagePanel);

縮小代碼

double scale_factor = 0.5;
imagePanel.getGraphics().drawImage(image.getImage(), 0, 100, (int)(imgWidth*=scale_factor), (int)(imgHeight*=scale_factor), imagePanel);  

有人可以建議一種僅在面板上顯示調整大小的圖像的方法嗎?
這就是縮小的樣子。 打開新圖片時也會發生相同的問題。
我嘗試重新粉刷面板,但隨后一切都消失了。

這就是縮小的樣子

那是因為imagePanel.getGraphics()並不是Swing中自定義繪畫的工作方式。 相反,創建一個自定義類,該類super.paintComponentJPanel類,並覆蓋它的paintComponent方法,在那里繪制縮放后的圖像(確保首先調用super.paintComponent )。

有關更多詳細信息,請參見“ AWT中的繪畫”和“搖擺執行自定義繪畫

例如:

暫無
暫無

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

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