Sweeper
Sweeper

Reputation: 271410

What are the alternatives for custom drawing in SpriteKit?

I want to make a sprite node like this:

|---------|
|some text|
|_________|

Which is just some text that is contained in a frame.

In UIKit, I would just simply create a custom view and override drawRect. I thought this can also be done with sprites or nodes. But the disappointing news is, I can't. The docs says explicitly that you can't do custom drawing.

I mean the above is such a simple object. I need to create two sprites (SKSpriteNode for the frame and SKLabelNode for the text) just for this? That's just too annoying for such a simple thing!

Moreover, what if I want to make a button darker when the user taps on it? If custom drawing were possible, I can just draw a grey layer with some alpha on the top when touchesBegan. But now I need 2 different textures (the normal one and the darker one) to do this!

Isn't this just too hard to do? I am sure there must be another, easier, way. Can you tell me how?

Upvotes: 0

Views: 397

Answers (1)

Chris Slowik
Chris Slowik

Reputation: 2879

You could set your button node up like this:

let buttonText = SKLabelNode(text: "Button")
let buttonBG = SKSpriteNode(imageNamed: "buttonTexture")
let button = SKNode()
button.addChild(buttonBG)
button.addChild(buttonText)

If you want to do something like apply a 35% black overlay to the button to darken it, you would do something like this to the button texture in touchesBegan:

buttonBG.runAction(SKAction.colorizeWithColor(UIColor.blackColor(), colorBlendFactor: 0.35, duration: 0.18))

And in touchesEnded:

buttonBG.runAction(SKAction.colorizeWithColor(UIColor.blackColor(), colorBlendFactor: 0.0, duration: 0.18))

Note that you can't actually apply this action to the parent node in this case because its not a sprite node.

Upvotes: 1

Related Questions