11

I'm interested if an SKSpriteNode can be made to imitate the behavior of a UIView where I can specify border and corner radius?

self.view.layer.borderColor = [UIColor lightGrayColor].CGColor;
self.view.layer.borderWidth = 2;
self.view.layer.cornerRadius = 2;
self.view.layer.masksToBounds = YES;
CodeBender
  • 35,668
  • 12
  • 125
  • 132
Alex Stone
  • 46,408
  • 55
  • 231
  • 407
  • See Here [link](http://stackoverflow.com/questions/21695305/skspritenode-create-a-round-corner-node?answertab=active#tab-top) – Blind Ninja Nov 29 '14 at 05:01

3 Answers3

16

The following is a simple, dropin extension for SKSpriteNode that will allow you to draw a border with a given color around your node.

import SpriteKit

extension SKSpriteNode {
    func drawBorder(color: UIColor, width: CGFloat) {
        let shapeNode = SKShapeNode(rect: frame)
        shapeNode.fillColor = .clear
        shapeNode.strokeColor = color
        shapeNode.lineWidth = width
        addChild(shapeNode)
    }
}
zekel
  • 9,227
  • 10
  • 65
  • 96
CodeBender
  • 35,668
  • 12
  • 125
  • 132
5

Not natively. Though you can just add a SKShapeNode as child whose path you create with CGPathCreateWithRoundedRect.

CodeSmile
  • 64,284
  • 20
  • 132
  • 217
2
extension SKSpriteNode {

    func drawBorder(color: UIColor, width: CGFloat) {

        for layer in self.children {
        
            if layer.name == "border" {
            
                layer.removeFromParent()
            
            }
        
        }
    
        let imageSize = self.texture?.size()
    
        let lineWidth = (imageSize!.width / self.size.width) * width
    
        let shapeNode = SKShapeNode(rect: CGRect(x: -imageSize!.width/2, y: -imageSize!.height/2, width: imageSize!.width, height: imageSize!.height))
        shapeNode.fillColor = .clear
        shapeNode.strokeColor = color
        shapeNode.lineWidth = lineWidth
        shapeNode.name = "border"
        shapeNode.zPosition = 1001
        self.addChild(shapeNode)
    
        self.zPosition = 1000

    }

}
Michael N
  • 436
  • 5
  • 6