NEW: Master Swift design patterns with my latest book! >>

How to emit particles using CAEmitterLayer

Written by Paul Hudson    @twostraws

Believe it or not, iOS has a built-in particle system that works great in all UIKit apps and is immensely customizable. To get started you need to create a CAEmitterLayer object and tell it how to create particles: where it should create them, how big the emitter should be, and what types of particles should exist.

The "type of particles" part is handled by CAEmitterCell, which covers details like how fast to create, how long they should live, whether they should spin and/or fade out, what texture to use, and more. You can add as many CAEmitterCells to a CAEmitterLayer as you need.

Here's some example code to get you started. This creates particles of three different colors, all falling and spinning down from the top of the screen. The image "particle_confetti" is just a small white triangle that I drew by hand – you should replace that with something more interesting.

func createParticles() {
    let particleEmitter = CAEmitterLayer()

    particleEmitter.emitterPosition = CGPoint(x: view.center.x, y: -96)
    particleEmitter.emitterShape = kCAEmitterLayerLine
    particleEmitter.emitterSize = CGSize(width: view.frame.size.width, height: 1)

    let red = makeEmitterCell(color: UIColor.red)
    let green = makeEmitterCell(color: UIColor.green)
    let blue = makeEmitterCell(color: UIColor.blue)

    particleEmitter.emitterCells = [red, green, blue]

    view.layer.addSublayer(particleEmitter)
}

func makeEmitterCell(color: UIColor) -> CAEmitterCell {
    let cell = CAEmitterCell()
    cell.birthRate = 3
    cell.lifetime = 7.0
    cell.lifetimeRange = 0
    cell.color = color.cgColor
    cell.velocity = 200
    cell.velocityRange = 50
    cell.emissionLongitude = CGFloat.pi
    cell.emissionRange = CGFloat.pi / 4
    cell.spin = 2
    cell.spinRange = 3
    cell.scaleRange = 0.5
    cell.scaleSpeed = -0.05

    cell.contents = UIImage(named: "particle_confetti")?.cgImage
    return cell
}

Available from iOS 5.0 – see Hacking with Swift tutorial 37

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

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

Learn Swift faster!

Take your Swift learning to the next level: buy the Hacking with Swift e-book and get bonus material to help you learn faster!

Click here to visit the Hacking with Swift store >>