Question

So I have a tile image tile.png and I'm trying to create a tiled map all across the window. I'm building this as an applet. This is what my paint method looks like, but its not effective. When I run the applet it takes about 2 seconds and the entire screen is painted from left to right with the image, rather than everything rendered at once. Also, it all looks like one large tile.png rather than 40 small instances of tile.png

public void paint(Graphics g)
{
    Image tile=getImg("tile.png");
    int width=this.getWidth();
    int height=this.getHeight();

    int x;
    int y;
    for (x=0; x<= width; x++)
    {
        for (y=0; y<= height; y++)
        {
            g.drawImage(tile, x, y, this);
        }
    }
}

Btw the tile.png file is 10 x 10 pixels, this is the actual img:

tile.png http://img12.imageshack.us/img12/1368/tile.png

Edit: Using the code below and by improving the tile image i fixed this. Here's my new tile img in case it helps someone:

tile-new.png

Was it helpful?

Solution

    for (x=0; x<= width / tileWidth; x++)
    {
            for (y=0; y<= height / tileHeight ; y++)
            {
                    g.drawImage(tile, x * tileWidth, y * tileHeight, this);
            }
    }

You need to offset by the width/height of the tile.

OTHER TIPS

Just as a side note, you are probably going to want to start checking your "Clip Region" at some point and not drawing stuff outside that region. Your code is set up pretty well to do that.

The other thing you could do to speed it up is "Double Buffer". Create a component the size of your map, call getGraphics() for that component, do all your drawing to this new graphics object, then just draw your component to the real Graphics object passed into your paint method.

A nice thing about this is that you can draw your entire map before you ever hit the paint statement, then slap it out instantly.

Google Double Buffering in Java for more info.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top