Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create SKTexture with rounded corners without using a mask

I wish to create a simple node with facebook profile picture of a user, where the picture has rounded corners (or a complete circle). I create the node as follows:

SKNode *friend = [[SKNode alloc] init];

SKTexture *texture = [SKTexture textureWithImage:user[@"fbProfilePicture"]];                
SKSpriteNode *profilePic = [SKSpriteNode spriteNodeWithTexture:texture];

[friend addChild:profilePic];

I could not find any proper documentation to create the image with rounded corners, other than using SKCropNode (which seems to be a bad workaround)

like image 694
Yuvals Avatar asked Apr 06 '14 07:04

Yuvals


1 Answers

This is how it looks in Swift by translating the above answer, Sebastian's answer. The method receives the name of the picture and returns a node with rounded corners.

class func roundSquareImage(imageName: String) -> SKSpriteNode {
            let originalPicture = UIImage(named: imageName)
            // create the image with rounded corners
            UIGraphicsBeginImageContextWithOptions(originalPicture!.size, false, 0)
            let rect = CGRectMake(0, 0, originalPicture!.size.width, originalPicture!.size.height)
            let rectPath : UIBezierPath = UIBezierPath(roundedRect: rect, cornerRadius: 30.0)
            rectPath.addClip()
            originalPicture!.drawInRect(rect)
            let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext();

            let texture = SKTexture(image: scaledImage)
            let roundedImage = SKSpriteNode(texture: texture, size: CGSizeMake(originalPicture!.size.width, originalPicture!.size.height))
            roundedImage.name = imageName
            return roundedImage
        }
like image 143
cipri.l Avatar answered Oct 20 '22 16:10

cipri.l