简体   繁体   English

Swift - 将背景图像添加到Spritekit场景

[英]Swift - Add a background image to a Spritekit scene

Here's my code, i didn't use asset catalog for my image InterfaceBakground.jepg. 这是我的代码,我没有使用资产目录作为我的图像InterfaceBakground.jepg。 Instead, I just dragged this 2048x1535 image to the project. 相反,我只是将这个2048x1535图像拖到项目中。 But the image didn't appear the right way. 但图像看起来并不正确。 I want the image to display as the background image, fill the entire screen. 我希望图像显示为背景图像,填满整个屏幕。

import SpriteKit
import GameplayKit
class GameScene: SKScene {

    var background = SKSpriteNode(imageNamed: "InterfaceBakground.jpeg")


    override func didMove(to view: SKView) {
        background.position = CGPoint(x: self.size.height/2, y: self.frame.width/2)

        self.addChild(background)
    }

    override func update(_ currentTime: TimeInterval) {
        // Called before each frame is rendered
    }
}

I saw this on the internet which brings me a little inspiration: 我在网上看到这个给我带来了一些灵感:

But if you're using an image that is exactly the size of the screen, it may not appear where you expect. 但是,如果您使用的图像与屏幕大小完全相同,则可能无法显示在您期望的位置。 This is because addChild adds new sprites at position 0, 0 (bottom left corner) by default. 这是因为默认情况下addChild会在位置0,0(左下角)添加新的精灵。 If you want to use an image sized specifically for your screen, you'll have to change its position. 如果您想使用专门用于屏幕的图像,则必须更改其位置。

My question is, how to change the position, so it fits devices for different size displays? 我的问题是,如何改变位置,以适应不同尺寸显示器的设备? Thanks in advance. 提前致谢。

Try this code: 试试这段代码:

override func didMove(to view: SKView) {
    background.position = CGPoint(x: 0, y: 0)
    background.size.width = self.size.width
    background.size.height = self.size.height
    background.anchorPoint = CGPoint(x: 0.5,y: 0.5)

    self.addChild(background)
}

AnchorPoint (0.5,0.5) which centers the image in its position. AnchorPoint(0.5,0.5)将图像置于其中心位置。

I am not entirely sure, but I think that you can just set the spriteNode's height and width like this. 我不完全确定,但我认为你可以像这样设置spriteNode的高度和宽度。 I also change the anchorPoint just to be sure: 我也改变了anchorPoint以确保:

override func didMove(to view: SKView) {
        background.size.width = self.size.width
        background.size.height = self.size.height
        background.anchorPoint = CGPoint(x: 0, y: 0)


        self.addChild(background)
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM