Micro-interactions in SwiftUI: Animated Wave

Jean-Marc Boullianne

Jean-Marc Boullianne
Level Up Coding
Published in
4 min readSep 2, 2020

--

Wave in Background of ScrollView

Welcome back! This week’s posts cover an assortment of SwiftUI micro-interactions that I’ve made for my apps. The benefits these interactions bring can really help make your app feel polished and simple to use. Today’s micro-interactions are all based on my custom Wave shape.

If you found this tip helpful, please consider subscribing using this link, and if you aren’t reading this on TrailingClosure.com, please come check us out sometime!

SwiftUI Wave Shape

These animations all start with one thing in common and that’s my custom SwiftUI Shape struct, Wave. The way this shape works is by drawing a continuous wave from the leading to the trailing side of the frame. Wave has two properties which can change how the shape looks:

  • phase - The phase at which the wave starts
  • waveHeight - The height (or really the amplitude) of the wave.

Here’s the code for the Wave shape:

struct Wave: Shape {

var waveHeight: CGFloat
var phase: Angle

func path(in rect: CGRect) -> Path {
var path = Path()
path.move(to: CGPoint(x: 0, y: rect.maxY)) // Bottom Left

for x in stride(from: 0, through: rect.width, by: 1) {
let relativeX: CGFloat = x / 50 //wavelength
let sine = CGFloat(sin(relativeX + CGFloat(phase.radians)))
let y = waveHeight * sine //+ rect.midY
path.addLine(to: CGPoint(x: x, y: y))
}

path.addLine(to: CGPoint(x: rect.maxX, y: rect.midY)) // Top Right
path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY)) // Bottom Right

return path
}
}

Our First Example!

Yes, our first example! The Wave shape is all we need to start creating some amazing interactions for our apps. Check out this one I made using two Wave shapes placed inside a ScrollView. Notice how when the user scrolls, the phase of the waves are changed, and thus they appear to move across the screen.

--

--