How to fit Image size to JFrame Size?

别说谁变了你拦得住时间么 提交于 2019-11-27 14:48:49
MadProgrammer

First of all, I wouldn't be loading the image inside the paintComponent method, this method is call repeatedly (and some times in quick succession), you don't want to do anything that takes time to execute or consumes resources unnecessarily

Check out Java: maintaining aspect ratio of JPanel background image for suggestions on filling/fitting images to a given area

trashgod

You want the drawImage() that scales to the target container. See the article cited here for alternatives. For example,

g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
Bishoy Basily
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JPanel;

public class ImagePanel extends JPanel {

    Image image;

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

    @Override
    public void paintComponent(Graphics G) {
        super.paintComponent(G);
        G.drawImage(image, 0, 0, this.getWidth(), this.getHeight(), null);
    }

}

Then use the ImagePanel object method SetBackground like

imagePanel1.SetBackGround(ImageIO.read(new File("extensions/images/background.jpg")));

Its Easy. Follow this example,

public class BasePanel extends JPanel {

ImageIcon backImage;
public BasePanel() {
    backImage = new ImageIcon("src/images/welcome.png");
}

@Override
protected void paintComponent(Graphics g) {
    BufferedImage scaledImage = getScaledImage();
    super.paintComponent(g);
    g.drawImage(scaledImage, 0, 0, null);
}

private BufferedImage getScaledImage(){
    BufferedImage image = new BufferedImage(getWidth(),getHeight(), BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = (Graphics2D) image.createGraphics();
    g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY));
    g2d.drawImage(backImage.getImage(), 0, 0,getWidth(),getHeight(), null);

    return image;
}

}
AvB

you can try this :

Image img = new ImageIcon(ImageIO.read(new File("welcome.png"))
                               .getScaledInstance(WIDTH, HEIGHT, Image.SCALE_SMOOTH)));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!