Introduction

CAEmitterLayer is the api of choice to do particle effects in UIKit. Its powerful and very often overlooked. A lot of developers use 3rd party libraries to achieve effects that can be easily created using this powerful API.

We will be creating the confetti effect thats displayed on the sign up screen of the houseparty app.

CAEmitterLayer and CAEmitterCell

UIKit provides 2 classes for us to work with particle effects, CAEmitterLayer and CAEmitterCell. The CAEmitterLayer is the layer that emits, animates and renders the particle system. The CAEmitterCell represents the source of particles and defines the direction and properties of the emitted particles.

Setup

Lets begin with an empty xcode project. Start by creating a CAEmitterLayer in your main view controller

var emitter = CAEmitterLayer()
emitter.emitterPosition = CGPoint(x: self.view.frame.size.width / 2, y: -10)
emitter.emitterShape = kCAEmitterLayerLine
emitter.emitterSize = CGSize(width: self.view.frame.size.width, height: 2.0)
emitter.emitterCells = generateEmitterCells()
self.view.layer.addSublayer(emitter)

We create an emitter layer and place it outside the visible bounds of the screen. And then add it as a sublayer of our main view. The main particle generation logic is placed in the generateEmitterCells() method.

private func generateEmitterCells() -> [CAEmitterCell] {
var cells:[CAEmitterCell] = [CAEmitterCell]()
for index in 0..<16 {
    let cell = CAEmitterCell()
    cell.birthRate = 4.0
    cell.lifetime = 14.0
    cell.lifetimeRange = 0
    cell.velocity = CGFloat(getRandomVelocity())
    cell.velocityRange = 0
    cell.emissionLongitude = CGFloat(Double.pi)
    cell.emissionRange = 0.5
    cell.spin = 3.5
    cell.spinRange = 0
    cell.color = getNextColor(i: index)
    cell.contents = getNextImage(i: index)
    cell.scaleRange = 0.25
    cell.scale = 0.1   
    cells.append(cell)    
}  
    return cells
}

We create 16 emitter cells, i’m using 4 images (Rounded Rectangle, Triangle, Circle, Swirl) i add the images to the cell.contents via the getNextImage() method. When adding the images to your assests make sure to select Render As Template Image in your attributes inspector. We apply a different tint color to the images using the cell.color property. And thats it the code above gives us an effect very smillar to the one found in the house party app.

Confetti Example

Here is a link to the video of how it works

Conclusion

The core image layers provided by UIKit are often overlooked. They provide a robust api for creating beautiful particle, gradient and image effects. The complete source code of the above implementation can be found here.