iosswiftsprite-kitscenekit

SK3DNode unable to set scene's background color


I have this minimum reproducible code:


class GameViewController: UIViewController {
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    if let view = self.view as! SKView? {
      
      let scene = SKScene()
      let node3D = SK3DNode(viewportSize: CGSize(width: 200, height: 200))
      node3D.position = CGPoint(x: 100, y: 100)
      
      let scene3D = SCNScene()
      node3D.scnScene = scene3D
      scene.addChild(node3D)
      
      scene3D.background.contents = UIColor.red


      view.presentScene(scene)
      view.ignoresSiblingOrder = true
      view.showsFPS = true
      view.showsNodeCount = true
    }
  }
}

I set the background color for the scene kit content to be red, but the result is a dark color screen.


Solution

  • It is indeed strange, that UIColor.red is not working. Even CGColor is not working as expected. (According to the Documentation, it should work)

    But here is, how you can fix the problem. I hope, it matches you requirements.

    Scene Initialisation: Replace let scene = SKScene() with:

    let scene = SKScene(size: view.bounds.size)
    

    Background Color: Instead of using scene3D.background.contents = UIColor.red use a solid UIImage as the color source.

    scene3D.background.contents = UIImage(color: .red)
    

    In order to do so, you need to include this extension somewhere in your code. It will generate a UIImage with the given color:

    extension UIImage {
        convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
            UIGraphicsBeginImageContextWithOptions(size, false, 0)
            color.setFill()
            UIRectFill(CGRect(origin: .zero, size: size))
            let image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            
            guard let cgImage = image?.cgImage else { return nil }
            self.init(cgImage: cgImage)
        }
    }
    

    Result: (scroll down) Result Screen