How to set the background image for a SKScene?

久未见 提交于 2019-12-05 14:56:12

Use an SKSpriteNode centered in the scene:

-(id)initWithSize:(CGSize)size {    
    if (self = [super initWithSize:size]) {
        // Replace @"Spaceship" with your background image:
        SKSpriteNode *sn = [SKSpriteNode spriteNodeWithImageNamed:@"Spaceship"];

        sn.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));
        sn.name = @"BACKGROUND";

        [self addChild:sn];
    }
    return self;
}

swift 4 version:

    let background = SKSpriteNode(imageNamed: "CheckIcon")
    background.size = frame.size
    background.position = CGPoint(x: frame.midX, y: frame.midY)
    addChild(background)
MB_iOSDeveloper

This solution helped me :

Put your code which calls/adds the scene from viewDidLoad to viewWillLayoutSubviews

- (void)viewWillLayoutSubviews
    {
    [super viewWillLayoutSubviews];

    // Configure the view.
    SKView * skView = (SKView *)self.view;
    skView.showsFPS = YES;
    skView.showsNodeCount = YES;

    // Create and configure the scene.
    SKScene * scene = [MyScene sceneWithSize:CGSizeMake(skView.bounds.size.width*2,skView.bounds.size.height*2)];
    scene.scaleMode = SKSceneScaleModeAspectFill;

    // Present the scene.
    [skView presentScene:scene];
}

As far as I know the reason for this is that the skView.boundsare different when the view is about to be layed out and when the view is shown. In general I found that the height and width are switched.

I found this solution from here: Background image size Sprite Kit Game

Here's a more elegant way, to ensure no matter what resolution you have now or in future, that your image will be the size of your background.

If you want to support banner ads, you'll have to reduce the height by 50 or 32 device units, and move the position up/down 25 or 16 pixels (portrait or landscape). I also recommend having a different image for landscape vs portrait if you want to support both, or you'll have to start letter-boxing.

In the scene...

SKSpriteNode* background = [SKSpriteNode spriteNodeWithImageNamed:@"myBackground"];
background.size = self.frame.size;
background.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));
[self addChild:background];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!