vzm
vzm

Reputation: 2450

How to set the background image for a SKScene?

Since currently it is not possible to set the color to of a SKScene to clearColor, by doing

-(id)initWithSize:(CGSize)size {
    if (self = [super initWithSize:size]) {


        self.backgroundColor = [SKColor clearColor];

    }
    return self;
}

As seen here: LINK

Then how can one set the background image for a SKScene? Please be as specific as possible, sample code would be great!

Upvotes: 5

Views: 11136

Answers (4)

Paul Lehn
Paul Lehn

Reputation: 3332

swift 4 version:

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

Upvotes: 7

GilesDMiddleton
GilesDMiddleton

Reputation: 2320

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];

Upvotes: 0

MB_iOSDeveloper
MB_iOSDeveloper

Reputation: 4198

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

Upvotes: 0

godel9
godel9

Reputation: 7390

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;
}

Upvotes: 5

Related Questions