iOS

Mesh Gradients: Custom and Animating View in SwiftUI


Mesh gradients represent a highly refined solution to linear and radial gradients and are built on the concept of a grid containing certain points. Every point in the grid is able to use an independent color which will enable the single hues to glide quickly and effortlessly across in every direction from one color to the next creating a true aesthetic sight. The elements of this technique are fine-tuned to each point within the three axes of a grid, allowing for the formation of complex and moving gradients.

Creating a Mesh Gradient

In SwiftUI, it is very simple to make a mesh gradient, which is simply a grid of points to which you assign colors. The following code example demonstrates the creation of a basic mesh gradient:

MeshGradient(width: 3, height: 3, points: [  .init(0, 0), .init(0.5, 0), .init(1, 0),  .init(0, 0.5), .init(0.5, 0.5), .init(1, 0.5),  .init(0, 1), .init(0.5, 1), .init(1, 1) ], colors: [  .red, .purple, .indigo,  .orange, .white, .blue,  .yellow, .green, .mint ]) 

In this instance, we generate the network of three coordinates 3X3 points with certain color points. This gives a gradient effect in the transition from one color to the other and hence creates a mesh of colors.

You can experiment with different grid points and color values to achieve various visual effects:

 

MeshGradient(  width: 3,  height: 3,  points: [  .init(0, 0), .init(0.5, 0), .init(1, 0),  .init(0, 0.5), .init(0.3, 0.5), .init(1, 0.5),  .init(0, 1), .init(0.5, 1), .init(1, 1)  ],  colors: [  .red, .purple, .indigo,  .orange, .cyan, .blue,  .yellow, .green, .mint  ] ) 

Animating a Mesh Gradient

Animating a mesh gradient involves changing the positions of points or colors dynamically. Here's a simple way to animate using SwiftUI:

 

 

import SwiftUI struct MeshGradientView: View {  @State var isAnimating = false  var body: some View {  MeshGradient(width: 3, height: 3, points: [  [0.0, 0.0], [0.5, 0.0], [1.0, 0.0],  [0.0, 0.5], [isAnimating ? 0.1 : 0.8, 0.5], [1.0, isAnimating ? 0.5 : 1],  [0.0, 1.0], [0.5, 1.0], [1.0, 1.0]  ], colors: [  .purple, .indigo, .purple,  isAnimating ? .mint : .purple, .blue, .blue,  .purple, .indigo, .purple  ])  .edgesIgnoringSafeArea(.all)  .onAppear() {  withAnimation(.easeInOut(duration: 3.0).repeatForever(autoreverses: true)) {  isAnimating.toggle()  }  }  } } #Preview {  MeshGradientView() }

 

Conclusion

Mesh gradients offer flexibility for creating complex, dynamic visuals in SwiftUI. By combining grid point control with animations, you can generate stunning, continuously evolving gradient effects for your apps.

 

Ready to transform your business with our technology solutions?   Contact Us today to Leverage Our iOS Expertise.


iOS

Related Center Of Excellence