How to set the background image for a SKScene?

白昼怎懂夜的黑 提交于 2019-12-22 08:27:15

问题


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!


回答1:


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



回答2:


swift 4 version:

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



回答3:


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




回答4:


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


来源:https://stackoverflow.com/questions/19780638/how-to-set-the-background-image-for-a-skscene

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!