Introduction to SwiftUI Gradient

Hello, fellow developers! In this blog post, I'm going to show you how to create beautiful gradient colors in SwiftUI. Gradient colors are a great way to add some flair and personality to your app's UI, and they are super easy to implement with SwiftUI.

Let's get started!

First, we need to import SwiftUI in our file:

ContentView.swift
import SwiftUI

Next, we need to create a gradient object. A gradient object is a type that conforms to the ShapeStyle protocol, and it defines how to fill a shape with a gradient color. SwiftUI provides two built-in gradient types: LinearGradient and RadialGradient. We can create them by passing an array of colors and an angle or a center point, respectively.

For example, let's create a linear gradient with two colors: blue and purple. We can use the following code:

ContentView.swift
let linearGradient = LinearGradient(colors: [.indigo, .purple], startPoint: .topLeading, endPoint: .bottomTrailing)

We can also create a radial gradient with three colors: blue, green and orange. We can use the following code:

ContentView.swift
let radialGradient = RadialGradient(colors: [.blue, .green, .orange], center: .bottomTrailing, startRadius: 0, endRadius: 200)

Now that we have our gradient objects, we can use them to fill any shape we want. For example, let's create a circle and a rounded rectangle and fill them with our gradients:

ContentView.swift
var body: some View {
        VStack {
            Text("SwiftUI Gradient")
                .font(.system(.largeTitle, design: .rounded))
                .fontWeight(.bold)
                .foregroundStyle(
                    linearGradient
                )

            Circle()
                .fill(linearGradient)
                .frame(width: 200, height: 200)

            RoundedRectangle(cornerRadius: 20)
                .fill(radialGradient)
                .frame(width: 200, height: 300)
        }
        .padding()
    }

And that's it! We have created two beautiful gradient colors in SwiftUI. Here's how they look in the preview:

Light mode Screenshot

Screenshot of simple SwiftUI Gradient

As you can see, gradient colors are very easy to implement in SwiftUI, and they can make your app look more attractive and professional. You can experiment with different colors, angles, points and shapes to create your own unique gradients.

I hope you enjoyed this blog post and learned something new. Happy coding!

Email icon representing an email newsletter

Don't subscribe