How to draw a picture with Canvas?

0

I have this code and 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();
}
    
asked by anonymous 09.07.2017 / 04:15

1 answer

2

You can use method drawImage(Image, int, int, ImageObserver) " to draw an image in its 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 drawImage is the image to be drawn. There are several ways you can get an instance of Image , but one of the easiest is to use method ImageIO.read(File) . The two parameters int of method drawImage are x and y in Graphics where you want to draw the image. The last parameter ( ImageObserver ) you probably will not need, and you can always pass null there.

    
09.07.2017 / 07:33