How to draw an image with Canvas?

Asked

Viewed 279 times

0

I have this code and I want to draw an image:

public void render(){
    BufferStrategy bs = getBufferStrategy();
    if(bs == null)
    {
        createBufferStrategy(3);
        return;
    }

    Graphics g = bs.getDrawGraphics();

    g.dispose();
    bs.show();
}

1 answer

2


You can use the method drawImage(Image, int, int, ImageObserver) to draw an image in your Graphics:

public void render() {
    BufferStrategy bs = getBufferStrategy();
    if (bs == null) {
        createBufferStrategy(3);
        return;
    }

    File arquivoComImagem = new File(...);
    BufferedImage img = ImageIO.read(arquivoComImagem );
    Graphics g = bs.getDrawGraphics();
    g.drawImage(img, 0, 0, null);
    g.dispose();
    bs.show();
}

In this case, the first parameter of the drawImage is the image to be drawn. There are several ways if you get an instance of Image, but one of the easiest is to use the method ImageIO.read(File). The two parameters int of the method drawImage are the position x and y in the Graphics where you want to draw the image. The last parameter (the ImageObserver) you probably won’t need it, and you can always pass null there.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.