Java: maintaining aspect ratio of JPanel background image

前端 未结 4 2067
伪装坚强ぢ
伪装坚强ぢ 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 07:11

    I came up with this solution:

    public class ImageLabel extends JPanel {
    
        private Image image = null;
    
        public void setImage(Image img) {
            image = img;
            repaint();
        }
    
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
    
            if (image != null) {
    
                int imgWidth, imgHeight;
                double contRatio = (double) getWidth() / (double) getHeight();
                double imgRatio =  (double) image.getWidth(this) / (double) image.getHeight(this);
    
                //width limited
                if(contRatio < imgRatio){
                    imgWidth = getWidth();
                    imgHeight = (int) (getWidth() / imgRatio);
    
                //height limited
                }else{
                    imgWidth = (int) (getHeight() * imgRatio);
                    imgHeight = getHeight();
                }
    
                //to center
                int x = (int) (((double) getWidth() / 2) - ((double) imgWidth / 2));
                int y = (int) (((double) getHeight()/ 2) - ((double) imgHeight / 2));
    
                g.drawImage(image, x, y, imgWidth, imgHeight, this);
            }
        }
    }
    

提交回复
热议问题