Reflection ViewModifier

Building a reflection ViewModifier using SwiftUI

Pedro Antunes
2 min readMay 11, 2021

Now you understand how it works, let’s go to more components I have created using SwiftUI and try to explain how to use the current modifiers SwiftUI provide to us.

If you haven’t read my previous post you can access here.

I will start showing how to create some nice effects to use in different applications.

Reflection Effect

Cat reflected and floating
Cat reflection

So the idea is create a modifier that from a View generates a reflection underneath it relative the image.

To make it work we first need to understand the characteristics of this effect.

  1. make a copy of the current View.
  2. flip it vertically to make the result mirroring the View.
  3. change a little the opacity, so the result is not clear as the original one.
  4. add a gradient crop to hide part of the reflection
  5. offset the result away or close to the original View

Following the steps 1, 2, 3 and 5 we have the following result:

The result so far looks like this:

The cat is reflected, but we missed the gradient to hide part of it

To make the gradient effect we need to create a mask and applies a LinearGradient from any color to clear color.

The Gradient has 2 initalisers

init(colors: [Color])init(stops: [Gradient.Stop])

If you chose the Stop object you can specify the location, value between 0.0 and 1.0 where you want your colour to start.

The final code you can check below.

Final version of the reflection

It looks complex, but is simple when you start to build more Modifiers for SwiftUI.

I will try to publish more contents and tutorials here. ViewModifiers are the beginning of a series with Animatable and it is a really nice way to use ViewModifiers.

Hope it can be helpful.

Find me at Twitter: @peantunes

--

--