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

标签 ios swift sprite-kit

这是我的代码,我没有为我的图像 InterfaceBakground.jepg 使用 Assets 目录。相反,我只是将这个 2048x1535 图像拖到项目中。但是图像没有以正确的方式出现。我希望图像显示为背景图像,填满整个屏幕。

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

在网上看到这个,给了我一点启发:

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. If you want to use an image sized specifically for your screen, you’ll have to change its position.

我的问题是,如何改变位置,使其适合不同尺寸显示器的设备?提前致谢。

最佳答案

试试这段代码:

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) 使图像在其位置居中。

关于ios - Swift - 将背景图像添加到 Spritekit 场景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39940898/

相关文章:

ios - CoreBluetooth 在应用程序终止时建立外设连接

swift - 带填充、顶部垂直对齐、多行占位符文本的自定义文本字段

ios - 我正在尝试创建多个具有不同类的自定义单元格

ios - 如何在 iOS 中升级(而不是更新)应用程序?

ios - 带有文本字段的 UIAlertView 在 iOS 8 中不弹出键盘

ios - 存储数据库的脱机副本

ios - 如何在 SpriteKit 中使用 UITextView?

ios - spriteKit 碰撞不起作用

ios - 如何在 Spritekit 中创建一个 SKActions 数组

ios - swift 2 : Instance Member cannot be used on type "View Controller"