Adjust the intensity of colors in SwiftUI views
In SwiftUI, we can use the convenient brightness(_:) modifier to adjust the brightness of colors in our views. It accepts a Double
value, where passing 0
keeps the original color, and a value of 1
makes the color fully white.
Here’s an example of how we can use it to lighten a color:
ForEach(0..<8) { num in
Color.purple
.brightness(Double(num) * 0.1)
}
This creates a gradient effect, transitioning the purple color from its original shade to almost white.
We can also use negative values with the brightness(_:)
modifier to darken a color as it approaches -1
:
ForEach(0..<8) { num in
Color.purple
.brightness(Double(num) * -0.1)
}
This results in a gradient effect where the purple transitions from its original shade to almost black.
If you have older iOS apps and want to enhance them with modern SwiftUI features, check out my book Integrating SwiftUI into UIKit Apps. It provides detailed guidance on gradually adopting SwiftUI in your UIKit projects. Additionally, if you're eager to enhance your Swift programming skills, my latest book Swift Gems offers over a hundred advanced tips and techniques, including optimizing collections, handling strings, mastering asynchronous programming, and debugging, to take your Swift code to the next level.