简体   繁体   English

如何在 Java 中创建平铺的 map?

[英]How to create a tiled map in Java?

So I have a tile image tile.png and I'm trying to create a tiled map all across the window.所以我有一个平铺图像 tile.png 并且我正在尝试在整个 window 上创建一个平铺的 map。 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.当我运行小程序时,大约需要 2 秒,整个屏幕都是从左到右绘制图像,而不是一次渲染所有内容。 Also, it all looks like one large tile.png rather than 40 small instances of tile.png此外,它看起来像一个大 tile.png 而不是 40 个小 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 文件是 10 x 10 像素,这是实际的 img:

tile.png http://img12.imageshack.us/img12/1368/tile.png 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:这是我的新瓷砖 img,以防它帮助某人:

瓷砖-new.png

    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.您需要偏移瓷砖的宽度/高度。

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.创建一个 map 大小的组件,为该组件调用 getGraphics(),对这个新图形 object 进行所有绘图,然后将组件绘制到传递给您的paint方法的真实图形 object。

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.关于这一点的好处是,您可以在您点击油漆声明之前绘制您的整个 map,然后立即将其拍掉。

Google Double Buffering in Java for more info. Java 中的 Google 双缓冲以获取更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM