Search code examples
cocos2d-android

Images handling in cocos2d android?


According to the different-2 screen resolution, can't use a single image for every device.

So, how to manage this thing in Cocos2d-android ?

or

Using setScale() is ok with it.


Solution

  • You have to create a method that can get the appropriate image according to screen size.

    There are following steps that will help you to get image

    1) Get the screen size and store that in a variable

    I have used as

    WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
    display = wm.getDefaultDisplay();
    if(display.getWidth()<=320)
    {
        GameCons.setSCreenSize(1);
    }else if(display.getWidth()<=480)
    {
        GameCons.setSCreenSize(2);
    }else if(display.getWidth()<=860)
    {
        GameCons.setSCreenSize(3);
    }else
    {
        GameCons.setSCreenSize(4);
    }
    

    Now we have screen size(1,2,3,4) store in variable screenSize

    2)Now assign the name to images you are using

    assuming if we have four images of player.png for four resolution then assign there name as player_1.png player_2.png player_3.png player_4.png

    These are same images for different resolution

    3) Now create method that will return a name of image as

    public static String getImageURI(String name) {
            if (screenSize== 1) {
                return name + "_1.png";
            } else if (screenSize== 2) {
                return name + "_2.png";
            } else if (screenSize== 3) {
                return name + "_3.png";
            } else {
                return name + "_4.png";
            }
        }
    

    4) Now you have to use this method in your layer while passing name to sprite or some other e.g:

    target = CCSprite.sprite(getImageURI("player"));
    

    You have to only pass the name before the underscore in method as above the real name is like player_1.png but we have only passes player

    the getImageURI will return a appropriate name according to the screen size assuming if we have screen size 2 then the getImageURI will return

    player_2.png

    so code will become like target = CCSprite.sprite("player_2.png");//getImageURI will return player_2.png