SKSpriteNode - create a round corner node?

前端 未结 8 1331
猫巷女王i
猫巷女王i 2020-12-01 05:10

Is there a way to make a SKSpriteNode round cornered? I am trying to create a Tile likesqaure blocks with color filled SKSpriteNode:

SKSpriteNode *tile = [SK         


        
相关标签:
8条回答
  • 2020-12-01 06:03

    Hope this helps:

    SKSpriteNode *make_rounded_rectangle(UIColor *color, CGSize size, float radius)
    {
        UIGraphicsBeginImageContext(size);
        [color setFill];
        CGRect rect = CGRectMake(0, 0, size.width, size.height);
        UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:radius];
        [path fill];
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        SKTexture *texture = [SKTexture textureWithImage:image];
        return [SKSpriteNode spriteNodeWithTexture:texture];
    }
    
    0 讨论(0)
  • 2020-12-01 06:08

    It's really this simple.......

    class YourSprite: SKSpriteNode {
    
        func yourSetupFunction() {
    
              texture = SKTexture( image: UIImage(named: "cat")!.circleMasked! )
    

    There's nothing more to it.

    You really can not use SKShapeNode.

    It's just that simple. It's an insane performance hit using SKShapeNode, it's not the right solution, it's pointlessly difficult, and the purpose of SKShapeNode just has no relation to this problem.

    Look at all them kitties!

    The code for circleMasked is this simple:

    (All projects that deal with images will need this anyway.)

    extension UIImage {
        
        var isPortrait:  Bool    { return size.height > size.width }
        var isLandscape: Bool    { return size.width > size.height }
        var breadth:     CGFloat { return min(size.width, size.height) }
        var breadthSize: CGSize  { return CGSize(width: breadth, height: breadth) }
        var breadthRect: CGRect  { return CGRect(origin: .zero, size: breadthSize) }
        
        var circleMasked: UIImage? {
            
            UIGraphicsBeginImageContextWithOptions(breadthSize, false, scale)
            defer { UIGraphicsEndImageContext() }
            
            guard let cgImage = cgImage?.cropping(to: CGRect(origin:
                CGPoint(
                    x: isLandscape ? floor((size.width - size.height) / 2) : 0,
                    y: isPortrait  ? floor((size.height - size.width) / 2) : 0),
                size: breadthSize))
            else { return nil }
            
            UIBezierPath(ovalIn: breadthRect).addClip()
            UIImage(cgImage: cgImage, scale: 1, orientation: imageOrientation)
                .draw(in: breadthRect)
            return UIGraphicsGetImageFromCurrentImageContext()
        }
    
    // classic 'circleMasked' stackoverflow fragment
    // courtesy Leo Dabius /a/29047372/294884
    }
    

    That's all there is to it.

    0 讨论(0)
提交回复
热议问题