Slow map in java

穿精又带淫゛_ 提交于 2019-12-06 16:44:09

First of all, you should not create the subimages for the tiles during each call. Strictly speaking, you should not call getSubimage at all for images that you want to paint: It will make the image "unmanaged", and this can degrade rendering performance by an order of magnitude. You should only call getSubimage for images that you do not want to render - for example, when you are initially creating individual images for the tiles.

You obviously already have a TileSet class. You could add a bit of functionality to this class so that you can directly access images for the tiles.

Your current code looks like this:

screen.drawImage(
    tileSet.getTileImage().getSubimage(
        tileSet.getTileX(tile), 
        tileSet.getTileY(tile),
        tileSet.getTileWidth(), 
        tileSet.getTileHeight()),
    x,y,null);

You could change it to look like this:

screen.drawImage(tileSet.getTileImage(tile), x,y,null);

The getTileImage(int tile) method suggested here could then obtain tiles that have been stored internally.

I'll sketch a few lines of code from the tip of my head, you'll probably be able to transfer this into your TileSet class:

class TileSet
{
    private Map<Integer, BufferedImage> tileImages;

    TileSet()
    {
        ....
        prepareTileImages();
    }

    private void prepareTileImages()
    {
        tileImages = new HashMap<Integer, BufferedImage>();

        for (int tile : allPossibleTileValuesThatMayBeInTheMap)
        {
            // These are the tiles that you originally rendered
            // in your "draw"-Method
            BufferedImage image = 
                getTileImage().getSubimage(
                    getTileX(tile), 
                    getTileY(tile),
                    getTileWidth(), 
                    getTileHeight());

            // Create a new, managed copy of the image,
            // and store it in the map
            BufferedImage managedImage = convertToARGB(image);
            tileImages.put(tile, managedImage);
        }
    }

    private static BufferedImage convertToARGB(BufferedImage image)
    {
        BufferedImage newImage = new BufferedImage(
            image.getWidth(), image.getHeight(),
            BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = newImage.createGraphics();
        g.drawImage(image, 0, 0, null);
        g.dispose();
        return newImage;
    }    

    // This is the new method: For a given "tile" value
    // that you found at map[x][y], this returns the
    // appropriate tile:
    public BufferedImage getTileImage(int tile) 
    {
        return tileImages.get(tile);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!