如何将图像加载到对象

时间:2016-06-21 16:04:47

标签: java image object rendering

我有一个对象类,在这个类中我有一个render方法。我想知道如何渲染图像。

我已经搜索了网络,但它是如此模糊,我对编码很新,所以这就是我最终要求的原因。

1 个答案:

答案 0 :(得分:0)

如果您使用的是JFrame,请将此JPanel添加到您的框架中:

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import javax.imageio.ImageIO;
import java.io.IOException;
import javax.swing.JPanel;

public class ImageView extends JPanel{
    private static final long serialVersionUID = 1L;

    private Image img;

    private int x = 0;
    private int y = 0;
    private int width = this.getWidth();
    private int height = this.getHeight();

    public ImageView(){
        super();

        try{
            img = ImageIO.read(new File("<img_path>.jpg"));
        }catch(IOException ex){
            // catch exception
        }
    }

    @Override
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;

        if(img!=null){
            g2d.drawImage(img, x, y, width, height, this);
        }
    }

    // your render method
    public void render(Image img){
        this.img = img;
        repaint();
    }

}