Smooth Core Animation Snow Effect
Recently I decided to create a snow animation in honor of the upcoming holidays! The actual animation is much smoother than the gif below but gives you an idea :)
Surprisingly, not a lot of code is required.
Steps for creating animation
- Create a
CAEmitterCell
from a snow flake asset - Create a
CAEmitterLayer
from theCAEmitterCell
- Make it Snow!
CAEmitterCell
The
CAEmitterCell
class represents one source of particles being emitted by aCAEmitterLayer
object. An emitter cell defines the direction and properties of the emitted particles. Emitter cells can have an array of sub-cells, which lets the particles themselves emit particles.
This class makes it really easy to configure the look and feel of the snow flakes. I highly encourage you to read their documentation to learn more!
let flakeEmitterCell = CAEmitterCell()
flakeEmitterCell.contents = UIImage(named: "snowFlake")?.cgImage
flakeEmitterCell.scale = 0.06
flakeEmitterCell.scaleRange = 0.3
flakeEmitterCell.emissionRange = .pi
flakeEmitterCell.lifetime = 20.0
flakeEmitterCell.birthRate = 40
flakeEmitterCell.velocity = -30
flakeEmitterCell.velocityRange = -20
flakeEmitterCell.yAcceleration = 30
flakeEmitterCell.xAcceleration = 5
flakeEmitterCell.spin = -0.5
flakeEmitterCell.spinRange = 1.0
CAEmitterLayer
A layer that emits, animates, and renders a particle system.
I found this class to be very powerful. For instance, setting the timeOffset allowed the animation to start at an offset so the user would automatically see snow flakes cover the entire screen from the start.
let snowEmitterLayer = CAEmitterLayer()
snowEmitterLayer.emitterPosition = CGPoint(x: view.bounds.width / 2.0, y: -50)
snowEmitterLayer.emitterSize = CGSize(width: view.bounds.width, height: 0)
snowEmitterLayer.emitterShape = kCAEmitterLayerLine
snowEmitterLayer.beginTime = CACurrentMediaTime()
snowEmitterLayer.timeOffset = 10
snowEmitterLayer.emitterCells = [flakeEmitterCell]view.layer.addSublayer(snowEmitterLayer)
Thats it!
Here is a GitHub link to see it in all in action.