keegan3d
keegan3d

Reputation: 11275

Unable to change SKView backgroundColor

This is with iOS 9. I am unable to set the background color of an SKView, it always renders with the default grey. Is there a way around this?

let frame = CGRect(x: 0, y: 0, width: 200, height: 100)
let spriteView = SKView(frame: frame)
spriteView.backgroundColor = .blueColor()
self.view.addSubview(spriteView)

When the above code is run the SKView is grey instead of blue. What I really want to be able to do is set allowsTransparency = true but I can't get that to work if I can't change the background color to clearColor.

Anyone else running into this? Any workarounds?

Update

Even with @Danilo's suggestion, this still displays as grey:

let frame = CGRect(x: 0, y: 0, width: 200, height: 100)
let spriteView = SKView(frame: frame)
spriteView.backgroundColor = .clearColor()
spriteView.allowsTransparency = true
spriteView.opaque = false

Update

Apparently setting the backgroundColor of an SKView has not effect, but if you do set it to anything then allowsTransparency = true doesn't work.

Upvotes: 2

Views: 1526

Answers (2)

miletliyusuf
miletliyusuf

Reputation: 1022

    let spriteView = SKView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
    let spriteKitScene = SKScene(size: spriteView.frame.size)
    spriteKitScene.backgroundColor = SKColor.blackColor()
    spriteView.presentScene(spriteKitScene)
    self.view.addSubview(spriteView)

Upvotes: 0

Unheilig
Unheilig

Reputation: 16292

In addition to adding a SKView, we need a SKScene that is to be presented by the SKView; we then adjust/change the backgroundColor of the SKScene. A node, in turn, will be added by the scene.

For example:

//create a SKView, which takes up the same frame as our view
let spriteView = SKView(frame: self.view.bounds)

//adding spriteView as a child view of our view
self.view.addSubview(spriteView)

//Here, we create a scene, which is the root object of
//the graph
let scene = SKScene(size: spriteView.frame.size)
scene.backgroundColor = .orangeColor()

//As said, we present the scene with our SKView
spriteView.presentScene(scene)

//Here, we create a node, which will be added by our scene
//This node takes up a size that you originally created and has the 
//background color set to blue
let nodeFrame = CGRect(x: 0, y: 0, width: 200, height: 100)
let node = SKSpriteNode(color: .blueColor(), size: nodeFrame.size)

//The following just serves to show how we can adjust the node's   
//position; I will leave that to you
node.position = CGPointMake(scene.frame.size.width - 200, scene.frame.size.height - 100)

//Finally, we add the node to our scene
scene.addChild(node)

Upvotes: 4

Related Questions