Gradients in text using foregroundStyle
In this post, we will explore how to create gradients in text using the foregroundStyle
modifier in SwiftUI. This technique allows for visually appealing text effects that can enhance the user interface of your applications.
What is .foreGroundStyle
?
ForegroundStyle is a SwiftUI modifier that allows you to apply a style to the foreground of a view, such as text. It can be used to create gradients, patterns, or other visual effects that enhance the appearance of text elements.
Usage
To use foregroundStyle
, you can apply it to a Text
view in SwiftUI. Here’s a simple example:
import SwiftUI
struct ContentView: View {
var body: some View {
Text("Hello, SwiftUI!")
.font(.largeTitle)
.foregroundStyle(
LinearGradient(
gradient: Gradient(colors: [.red, .blue]),
startPoint: .leading,
endPoint: .trailing
)
)
}
}
Old way (without foregroundStyle
and a mask)
This is the traditional way of applying a gradient to text before the introduction of foregroundStyle
. It involves using a mask to apply the gradient to the text.
Note: This does not work well with Emoji.
import SwiftUI
struct OldContentView: View {
var body: some View {
Text("Hello, SwiftUI!")
.font(.largeTitle)
.overlay {
LinearGradient(
colors: colors,
startPoint: startPoint,
endPoint: endPoint
)
.mask(
self
)
}
}
}
Combining the two approaches (for supporting older iOS versions)
To support older iOS versions that do not have the foregroundStyle
modifier, you can combine both approaches. This way, you can use foregroundStyle
on newer versions and fall back to the masking technique on older versions.
import SwiftUI
extension Text {
/// Make the foreground gradient
///
/// Create a gradient for the foreground of the text.
///
/// - Parameters:
/// - colors: Colors
/// - startPoint: Startpoint
/// - endPoint: End point
/// - Returns: self
@ViewBuilder
public func foregroundLinearGradient(
colors: [Color] = [.red, .blue, .green, .yellow],
startPoint: UnitPoint = .leading,
endPoint: UnitPoint = .trailing
) -> some View {
if #available(iOS 17, *) {
self.foregroundStyle(
LinearGradient(
colors: colors,
startPoint: startPoint,
endPoint: endPoint
)
)
} else {
self.overlay {
LinearGradient(
colors: colors,
startPoint: startPoint,
endPoint: endPoint
)
.mask(
self
)
}
}
}
}
Conclusion
The foregroundStyle
modifier in SwiftUI provides a powerful way to apply gradients and other styles to text. This enhances the visual appeal of your applications and allows for creative text effects. By using LinearGradient
, RadialGradient
, or AngularGradient
, you can easily create stunning text designs that stand out in your user interface.
Read more
- Snippet: @EnvironmentVariable • 1 minutes reading time.
- Thermal States on iOS • 3 minutes reading time.
- Xcode shortcuts • 3 minutes reading time.
Share
Share Bluesky Mastodon Twitter LinkedIn Facebook