【问题标题】:Scene with SpriteView and SwiftUI does not fill whole screen带有 SpriteView 和 SwiftUI 的场景不会填满整个屏幕
【发布时间】:2021-08-08 04:13:26
【问题描述】:

我正在尝试处理项目 1 并使用 SpriteKit 和 SwiftUI,但由于某种原因,我的 iPad 上的场景从未填满整个屏幕。

import SwiftUI
import SpriteKit

struct ContentView: View {
    var scene: SKScene {
        let screenWidth  = UIScreen.main.bounds.width
        let screenHeight = UIScreen.main.bounds.height
        
        let scene = GameScene()
        scene.size = CGSize(width: screenHeight, height: screenWidth)
        scene.scaleMode = .fill
        scene.backgroundColor = .green
        return scene
    }
    
    var body: some View {
        let screenWidth  = UIScreen.main.bounds.width
        let screenHeight = UIScreen.main.bounds.height
        
        print(screenWidth)
        
        return SpriteView(scene: scene)
            .frame(width: screenWidth, height: screenHeight)
            .ignoresSafeArea()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

现在看起来像这样:

任何想法我在这里缺少什么?

最大

【问题讨论】:

  • 尝试删除.frame(width: screenWidth, height: screenHeight),并将CGSize(width: screenHeight, height: screenWidth)替换为CGSize(width: screenWidth, height: screenHeight)
  • 即使我这样更改它也不会将棕色背景纹理缩放到全屏尺寸(GameScene 类的一部分)``` let background = SKSpriteNode(imageNamed: "road") background. zPosition = -1 // background.scale(to: CGSize(width: 1180, height: 700)) // background.scale(to: CGSize(width: CGFloat(1180), height: CGFloat(820))) addChild( background) ``` 我最后通过将背景放入 ZStack{} 中修复了它(更新了我的帖子)

标签: swiftui sprite-kit scenekit


【解决方案1】:

最后通过将背景放在 ContentView 的 ZStack() 中修复它

var body: some View {
        let screenWidth  = UIScreen.main.bounds.width
        let screenHeight = UIScreen.main.bounds.height
        
        ZStack{
            EmptyView()
            Image("road")
                .resizable()
                .aspectRatio(contentMode: .fill)
                .ignoresSafeArea()
            
            SpriteView(scene: scene, options: [.allowsTransparency])
                .frame(width: screenWidth, height: screenHeight)
                .ignoresSafeArea()
        }
    }
}

由于某种原因,当我将纹理添加为 GameScene 类的一部分时,无论我尝试何种比例,它都不会将纹理放大到全屏大小:

let background = SKSpriteNode(imageNamed: "road")
        
        background.zPosition = -1
//      background.scale(to: CGSize(width: 1180, height: 700))
//      background.scale(to: CGSize(width: CGFloat(1180), height: CGFloat(820)))
        addChild(background)

【讨论】:

    【解决方案2】:

    您在场景属性中具有宽度高度和高度宽度参数。 (@aheze 在评论中是如何提到的)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-14
      • 1970-01-01
      • 1970-01-01
      • 2017-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多