【问题标题】:How to deal with the black area beyond the SKView() (In Swift Playground)如何处理 SKView() 之外的黑色区域(在 Swift Playground 中)
【发布时间】:2021-04-09 09:10:02
【问题描述】:

我正在尝试在 Swift Playground 中运行的工作中使用 SpriteKit+SwiftUI。这是我的一些代码

struct SwiftUI: View {
    var body: some View {
         Test() 
    }
}
struct Test: UIViewRepresentable {
    func makeUIView(context: Context) -> SKView {
        let sceneView = SKView()
        let gameScene = GameScene()
        gameScene.size = CGSize(width: 500, height: 600)
        gameScene.scaleMode = .aspectFit
        sceneView.presentScene(gameScene)
        return sceneView
    }
    func updateUIView(_ uiView: SKView, context: Context) {
    }
}

它运行良好,但在我的 SKView 之外总是有这个可怕的黑色区域,如下图所示。
Black area in the View
我曾尝试更改sceneView.backgroundcolor,或更改gameScene.sizesceneView.size,但这些都不起作用。 ??? 非常感谢您能给我一些建议!

【问题讨论】:

    标签: swift swiftui sprite-kit


    【解决方案1】:

    问题是对Test() 的调用也需要明确设置帧大小。否则,Test 视图会占用整个可用屏幕空间,而场景视图仅占用该空间的一部分。

    下面的示例与您发布的示例相同,在Test() 上设置了一个明确的框架(和一个虚拟的GameScene)。这在操场上有效,结果只是一个紫色方块,视野之外没有黑色区域:

    import SwiftUI
    import SpriteKit
    import PlaygroundSupport
    
    let width: CGFloat = 500
    let height: CGFloat = 500
    
    struct ContentView: View {
        var body: some View {
             Test()
                .frame(width: width, height: height)
        }
    }
    struct Test: UIViewRepresentable {
        func makeUIView(context: Context) -> SKView {
            let sceneView = SKView()
            let gameScene = GameScene()
            gameScene.size = CGSize(width: width, height: height)
            gameScene.scaleMode = .aspectFit
            sceneView.presentScene(gameScene)
            return sceneView
        }
        func updateUIView(_ uiView: SKView, context: Context) {
        }
    }
    
    class GameScene: SKScene {
        override func didMove(to view: SKView) {
            let node = SKShapeNode(rect: CGRect(x: 0, y: 0, width: size.width, height: size.height))
            node.fillColor = .purple
            addChild(node)
        }
    }
    
    
    PlaygroundPage.current.setLiveView(ContentView())
    

    【讨论】:

      猜你喜欢
      • 2017-11-21
      • 2017-07-17
      • 1970-01-01
      • 2021-04-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-22
      • 2023-02-10
      • 2020-10-20
      相关资源
      最近更新 更多