Search code examples
javagraphicsbufferedimagegraphics2djava-2d

Why is an image displayed with Graphics.drawImage() in Java not like I drew it


I have BufferedImage that stores .png image (320 x 240) and I draw it on Сanvas with Graphics.drawImage(). But if you look closely, for example, the cross 3 by 3 pixels is actually 4 by 3 pixels. Look my question in the picture: enter image description here

GameContainer render method:

public void render() {
    bs = window.canvas.getBufferStrategy();
    if (bs == null) {
        window.canvas.createBufferStrategy(3);
        return;
    }
    g = (Graphics2D) bs.getDrawGraphics();
    gm.render(g);
    g.dispose();
    bs.show();
}



GameManager render method:

public void render(Graphics2D g) {
    b.render(g);
}



Background render method:

public void render(Graphics2D g) {
    g.drawImage(image, 0, 0 , null);
}

Solution

  • You may probably be using one of the overloads of drawImage() that scales the image to fit inside a particular area. You may take a look here: https://docs.oracle.com/javase/tutorial/2d/images/drawimage.html The following paragraph: For example, the following overload of the drawImage() method enables you to draw as much of a specified area of the specified image as is currently available, scaling it to fit inside the specified area of the destination drawable surface:

    boolean Graphics.drawImage(Image img, int dstx1, int dsty1, int dstx2, int dsty2, int srcx1, int srcy1, int srcx2, int srcy2, ImageObserver observer);