Java: maintaining aspect ratio of JPanel background image

前端 未结 4 2052
伪装坚强ぢ
伪装坚强ぢ 2020-11-21 06:28

I have a JPanel with a painted background image and a layout manager holding other smaller images, all of this inside a JFrame. The background imag

4条回答
  •  被撕碎了的回忆
    2020-11-21 06:55

    For anyone interested ammending the PaintComponent method by MadProgrammer as follows allows much quicker display update

            @Override
            protected void paintComponent(Graphics g) {
                Graphics2D g2d = (Graphics2D) g;
                super.paintComponent(g);
    
                double scaleFactor = Math.min(1d, getScaleFactorToFit(new Dimension(image.getWidth(), image.getHeight()), getSize()));
    
                int scaleWidth = (int) Math.round(image.getWidth() * scaleFactor);
                int scaleHeight = (int) Math.round(image.getHeight() * scaleFactor);
    
                //Image scaled = image.getScaledInstance(scaleWidth, scaleHeight, Image.SCALE_SMOOTH);
    
                int width = getWidth() - 1;
                int height = getHeight() - 1;
    
                int x = (width - scaleWidth) / 2;
                int y = (height - scaleHeight) / 2;
    
                g2d.drawImage(image, x, y, scaleWidth, scaleHeight, this);
    
            }
    

提交回复
热议问题