How to add animation to MeshGradient in SwiftUI?

SwiftUI now support for Mesh Gradients.

Mesh gradients are useful when you want a dynamic background, or need to add some visual distinction to a surface. Mesh Gradients are made from a grid of points. Each of these of these points has a color associated with it.

The colors blend together smoothly, and points that are closer together have sharper color transition.

In order to create a Mesh Gradient, I’ll use the new MeshGradient view.
I’ll define the rows and columns of my grid using the width and height parameters.

In this case, I’ll use a 3 by 3 grid. Next, we’re going to define where the X and Y coordinates on this 3×3 grid are located. Points in the grid are defined using float values. When used as a view, these floats take a value from 0 to 1 on the X and Y axis. Finally, I’ll add a corresponding color for each of these points. This creates our mesh gradient! Right now it looks a bit like a linear gradient.

Sample code:

MeshGradient(
width: 3,
height: 3,
points: [
[0.0, 0.0], [0.5, 0.0], [1.0, 0.0],
[0.0, 0.5], [0.5, 0.5], [1.0, 0.5],
[0.0, 1.0], [0.5, 1.0], [1.0, 1.0]
], colors: [
.red, .red, .red,
.black, .red, .black,
.black, .red, .black
])
.edgesIgnoringSafeArea(.all)

If I move the X and Y coordinates of the center point, the colors move to match the new position! Mesh gradients are a nice way to add color effects to your app, and you can use them to create all sorts of visual effects.

They can be purely decorative, but you can also use them to match a surface with imagery, or even signal that something has changed through a mesh gradient animation! Play around with values, like the position of control points, grid size, and color palette.

Sample code for animated MeshGradient:

TimelineView(.animation) { timeline in
let x = (sin(timeline.date.timeIntervalSince1970) + 1) / 2
MeshGradient(
width: 3,
height: 3,
points: [
[0.0, 0.0], [0.5, 0.0], [1.0, 0.0],
[0.0, 0.5], [Float(x), 0.5], [1.0, 0.5],
[0.0, 1.0], [0.5, 1.0], [1.0, 1.0]
], colors: [
.red, .red, .red,
.black, .red, .black,
.black, .red, .black
])
.edgesIgnoringSafeArea(.all)
}

Tweaking parameters, and exploring the edges of what’s visually possible will lead you far beyond any ideas you have at the beginning, make something new!

Conclusion

SwiftUI comes with lot of things to learn. Keep Learning! 
Happy Coding 🙂