-->

Can I add a border to an SKSpriteNode, similar to

2020-08-17 18:03发布

问题:

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;

回答1:

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



回答2:

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)
    }
}


回答3:

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

    }

}