UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

How to crop a sprite using SKCropNode

Swift version: 5.6

Paul Hudson    @twostraws   

SpriteKit has a dedicated node type for handling cropping, and you can add things to it, position it where you want, then add it to your scene just like any other node.

However, its role is to crop the nodes it contains: when you assign a node to its maskNode property, SpriteKit looks at the colors of the mask and uses that to crop all the child nodes of the crop node. So, you might create an SKCropNode with five child nodes, then give it a circular mask node so that parts of the children are invisible. Everything that has a color in the mask won’t be cropped, and everything that is invisible will be.

Let’s look at some code. First you create and position your crop node:

let cropNode = SKCropNode()
cropNode.position = CGPoint(x: 50, y: 50)

Next you set its maskNode property to any SpriteKit node. Using a sprite node is easy enough:

cropNode.maskNode = SKSpriteNode(imageNamed: "cropMask")

Third you create a child node, position it inside the crop node, then add it to the crop node:

childNode = SKSpriteNode(imageNamed: "child")
childNode.position = CGPoint(x: 0, y: -90)
childNode.name = "character"
cropNode.addChild(childNode)

Finally add the crop node to your main scene:

addChild(cropNode)

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Available from iOS 7.1

Similar solutions…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.