How to scale background image rather than screen size?

Hi everybody ,
How to scale background image rather than screen size in Cocos2d-x 3 ?

This is one option for you:

cocos2d:Sprite* bgS = cocos2d::Sprite::create("game_bg.png");
s_visibleRect = Director::getInstance()->getOpenGLView()->getVisibleRect();
float scaleY = s_visibleRect.size.height/bgS->getContentSize().height;
float scaleX = s_visibleRect.size.width/bgS->getContentSize().width;
if(scaleX>scaleY){
    bgS->setScale(scaleX);
}else{
    bgS->setScale(scaleY);
}
bgS->setPosition(Point(s_visibleRect.origin.x+s_visibleRect.size.width/2, s_visibleRect.origin.y+s_visibleRect.size.height/2));
this->addChild(bgS);
1 Like

@catcheruk Thanks

@catcheruk
This worked for me except I had to switch the X and Y like so:

if (scaleX > scaleY) {
    bgS->setScale(scale**Y**);
}else{
    bgS->setScale(scale**X**);
}

There is very good tutorial for doing that : https://www.youtube.com/watch?v=tpdyfiTlcJg&list=PLZ1QII7yudbf2opgE-EM2ac_qDpVpjXFc

Good to know, it’s my mistake :smile:

@yagoub Wow, that was a really detailed tutorial! Thanks so much, that’s stupendous. Now to try to mimic that in JavaScript…this may be tough!