Categories
iOS macOS Swift SwiftUI

Animating a custom wave shape in SwiftUI

Wave shape with red button on top of it

Shape protocol in SwiftUI is used for defining views which render custom shapes. Shapes have one required method which takes in a rect and returns a Path. In addition to view protocol, shape conforms to Animatable protocol as well. Therefore we can quite easily make our custom shape to animate from one state to another. We’ll use two parameters for defining our Wave shape: amplitude and frequency. Amplitude dictates the height of the wave and frequency the distance between wave peaks.

Animating wave shape by changing amplitude and frequency
Animating wave shape.

SwiftUI view displaying an animatable wave shape

Let’s take a look on an example view which displays custom Wave shape. We’ll use @State property wrappers for storing amplitude and frequency because we want to change those values when running the app. Those properties are updated with random values when pressing a button. The wave has blue fill color, fixed height, and basic easeInOut animation. The animation is used when amplitude and/or frequency change.

struct ContentView: View {
@State private var amplitude = 10.0
@State private var frequency = 0.1
var body: some View {
ZStack {
Wave(amplitude: amplitude, frequency: frequency)
.fill(Color.blue)
.frame(height: 300.0)
.animation(.easeInOut(duration: 3))
Button(action: toggleAnimation, label: {
Text("Animate")
})
.padding(4)
.background(Color.red)
.cornerRadius(8)
.foregroundColor(.white)
}
}
func toggleAnimation() {
amplitude = amplitude <= 15.0 ? Double.random(in: 30.060.0) : Double.random(in: 5.015.0)
frequency = frequency <= 0.2 ? Double.random(in: 0.20.4) : Double.random(in: 0.050.2)
}
}
Content view rendering a wave shape with a button starting an animation.

Animatable wave shape

Like mentioned in the introduction, the Shape protocol defines a required method which has a rect argument and returns a Path. The path starts from the top left edge. Sine function is used for calculating y coordinates for every x coordinate with a 1 point step. Right, bottom and left edges are just straight lines.

Animatable protocol defines an animatableData property and because we have two parameters (amplitude and frequency) we’ll need to use AnimatablePair type. If there would be more parameters then AnimatablePair should contain one or more AnimatablePair types (and so on). Note that values in animatableData must conform to VectorArithmetic protocol which Double type already does.

When animation is running then SwiftUI calculates amplitude and frequency values based on the current animation frame and sets it to the animatableData property. Then new Path value is calculated and rendered.

struct Wave: Shape {
var amplitude: Double
var frequency: Double
func path(in rect: CGRect) -> Path {
let sinCenterY = amplitude
let path = CGMutablePath()
path.move(to: CGPoint(x: 0, y: sinCenterY))
let width = Double(rect.width)
for x in stride(from: 0, through: width, by: 1) {
let y = sinCenterY + amplitude * sin(frequency * x)
path.addLine(to: CGPoint(x: x, y: y))
}
path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))
path.addLine(to: CGPoint(x: rect.minX, y: rect.maxY))
path.addLine(to: CGPoint(x: Double(rect.minX), y: sinCenterY))
return Path(path)
}
var animatableData: AnimatablePair<Double, Double> {
get {
return AnimatablePair(amplitude, frequency)
}
set {
amplitude = newValue.first
frequency = newValue.second
}
}
}
view raw Wave.swift hosted with ❤ by GitHub
Animatable Wave shape.

Summary

We took a look at the Shape protocol and created a wave shape. In addition, we made the wave to animate from one amplitude and frequency state to a new state.

If this was helpful, please let me know on Mastodon@toomasvahter orĀ Twitter @toomasvahter. Feel free to subscribe to RSS feed. Thank you for reading.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s