Search code examples
androidgame-enginecocos2d-android

How to adjust images to all android screen devices using cocos2d android library without using xml layout for Game designing


I am new to Android Game development, I am facing problem with adjusting images to all different screen sizes of android.
Technology I am using cocos2d android library to design game.

Currently working code is :-

if(winSize.width>1250 && winSize.height>700)
    {
        background = CCSprite.sprite("bg480X800.png");

        float scalexx=winSize.width/background.getContentSize().width;
        float scaleyy=winSize.height/background.getContentSize().height;

        background.setScaleX(scalexx);
        background.setScaleY(scaleyy);
        //background.setScale(1.65f);

    }
    /* *************************1000-1250  ********************** */ 
    else if(winSize.width<1250 && winSize.width>1000 )
    {
        background = CCSprite.sprite("bg7.png");

        float scalexx=winSize.width/background.getContentSize().width;
        float scaleyy=winSize.height/background.getContentSize().height;

        background.setScaleX(scalexx);
        background.setScaleY(scaleyy);
        //background.setScale(1.0f);
    }
    else
    {
        background = CCSprite.sprite("bg480X800.png");

        //background.setScale(1.0f);
        float scalexx=winSize.width/background.getContentSize().width;
        float scaleyy=winSize.height/background.getContentSize().height;

        background.setScaleX(scalexx);
        background.setScaleY(scaleyy);

    }

Please tell me if you know better and smart coding that it adjust to all screen sizes


Solution

  • CGSize winSize = CCDirector.sharedDirector().displaySize();
    
    CCSprite background=CCSprite.sprite("background.png");
    
    background.setScaleX(winSize .width/background.getTexture().getWidth());
    background.setScaleY(winSize.height/background.getTexture().getHeight());
    background.setPosition(CGPoint.make(winSize.width/2, winSize.height/2));
    addChild(background);
    

    Set to exact , what is the screen size