Search code examples
iosswiftbackgroundsprite-kitskspritenode

SpriteKitNode Background Color


I am building a card game and have an image for the texture of my SpriteKit node. The image is a pdf image for the card artwork and I want to set the background color of the card (The blank space around the artwork). The image I have is just the artwork of the card and does not have any background detail. How can I set a background to this? Setting the "color" attribute in the SKSpriteNode init only changes the color of my image object. How can I access the color and the texture of the "blank space" behind the image while remaining in the width and size set in the super.init?

I don't want to change all my pdfs and add a white layer to the back because I may want to have some custom color changes for the background of the card while the game is playing. I have tried adding a SKShapeNode inside the init function (Example below), but that technically overlays on top of my Card SKSpriteNode and then the user can't click on the actual "Card". It seems like this should be fairly straightforward, but I have had a lot of trouble.

import SpriteKit

class Card: SKSpriteNode {

    init(image: String) {
        super.init(texture: SKTexture(imageNamed: image), color: .clear,
                   size: CGSize(width: K.cardSize[0], height: K.cardSize[1]))

        //Background
        let background = SKShapeNode(rectOf: CGSize(width: K.cardSize[0], height: K.cardSize[1]), cornerRadius: 15)
        background.fillColor = UIColor.white
        background.zPosition = -10
        addChild(background)
    }

}

Solution

  • Create 2 SKSpriteNodes like this

    class Card: SKSpriteNode {
    
        init(imageName: String) {
           let card = SKSpriteNode(imageNamed:imageName)
           //Create the rounded corner image without resorting to SKShapeNode
           UIGraphicsBeginImageContext(card.size)
               let context =  UIGraphicsGetCurrentContext()
               context.clear(rect)
               context.setFillColor(UIColor.white.cgColor)
               let rect = CGRect(origin: .zero, size:size)
               let path = UIBezierPath(roundedRect:rect, cornerRadius:0.15)
               path.fill()
               let image = context.makeImage();
           UIGraphicsEndImageContext();
    
           super.init(texture:SKTexture(cgImage:image))        
    
           card.isUserInteractionEnabled = false
           addChild(card)
        }
    
    }
    

    This will now treat your card image more like a texture than an interactive node.