Search code examples
cocos2d-xcocos2d-x-3.0

Cocos-2dx v3 centering background sprite problems


Here is my background image:

enter image description here

And here is some code that I would assume scales this image to fully fit the screen.

Size visibleSize = Director::getInstance()->getVisibleSize();
auto bg = Sprite::create("grad.png");
bg->setScale(visibleSize.width / bg->getContentSize().width, visibleSize.height / bg->getContentSize().height);
bg->setAnchorPoint(Vec2(0,0));
addChild(bg);

I would expect those 4 lines to create a background sprite that would cover the entire screen size. However, here's a screenshot of what I am actually getting on my iPhone6+:

Image isn't centered

If I change the first line to

Size visibleSize = Director::getInstance()->getWinSize();

Then this is what I get, which isn't quite right either:

enter image description here


Solution

  • Using VisibleSize is correct, you just need one more change:

    bg->setPosition(director->getVisibleOrigin());
    

    By default, cocos2d-x uses ResolutionPolicy::NO_BORDER, so the bottom part of winSize is likely to be cropped. getVisibleSize() returns the visible origin in Point rather then pixel.