How to apply Gradient Color for Text in SwiftUI?

SwiftUI Text – Gradient Foreground Color

To set gradient color for text in Text view, we may write an extension for View, with a new function that applies gradient color, and call this new function on Text view.

Example

In the following example, we have a Text view. We will write an extension for View class. The extension contains a function gradientColor() that accepts an array of colors, and use these colors for gradient computation.

ContentView.swift

import SwiftUI

struct ContentView: View {
    var body: some View {
        Text("Hello World!")
            .font(.title)
            .gradientForeground(colors: [.red, .blue])
    }
}

extension View {
    public func gradientForeground(colors: [Color]) -> some View {
        self.overlay(LinearGradient(gradient: .init(colors: colors),
                                    startPoint: .leading,
                                    endPoint: .trailing))
            .mask(self)
    }
}

In the gradientForeground() function, we have defined the starting point with leading edge, and the end point with trailing edge. The resulting output would be as shown in the following picture.

Screenshot

SwiftUI Text - Gradient Color
Gradient color from left to right

We can change these starting and ending points, and create gradient in different direction.

For example, let us create a gradient color for the font, in the direction of top to bottom.

ContentView.swift

import SwiftUI

struct ContentView: View {
    var body: some View {
        Text("Hello World!")
            .font(.title)
            .gradientForeground(colors: [.red, .blue])
    }
}

extension View {
    public func gradientForeground(colors: [Color]) -> some View {
        self.overlay(LinearGradient(gradient: .init(colors: colors),
                                    startPoint: .top,
                                    endPoint: .bottom))
            .mask(self)
    }
}

Screenshot

SwiftUI Text - Gradient Color
Gradient color from top to bottom

Also, we can have more than two colors for the gradient.

Let us modify the text view with gradient foreground with colors red, green and blue.

ContentView.swift

import SwiftUI

struct ContentView: View {
    var body: some View {
        Text("Hello World!")
            .font(.title)
            .gradientForeground(colors: [.red, .green, .blue])
    }
}

extension View {
    public func gradientForeground(colors: [Color]) -> some View {
        self.overlay(LinearGradient(gradient: .init(colors: colors),
                                    startPoint: .leading,
                                    endPoint: .trailing))
            .mask(self)
    }
}

Screenshot

SwiftUI Text - Gradient Color
Gradient with more than two colors

Summary

Summarising this SwiftUI Tutorial, we learned how to set gradient foreground color to the text in Text view.