I want to mix two colors in SwiftUI code. For eg: Green and Black with opacity 20%. The final color should be a mix these two colors. Is there any method other than using ZStack to achieve the same?
I want to mix two colors in SwiftUI code. For eg: Green and Black with opacity 20%. The final color should be a mix these two colors. Is there any method other than using ZStack to achieve the same?
2
Answers
Since you are working in iOS, you can take advantage of the fact that a SwiftUI
Color
can be created from aUIColor
.Using
UIColor.blend
from this answer you can create a blend of 2UIColor
s by specifying the colors and the intensity(0.0 ... 1.0)
for each. For example, to create a foreground color forText
that is 80%UIColor.green
and 20%UIColor.black
:Note: Just include the
UIColor extension
in any file in your project. It is a good practice to give extensions their own file(s), but you can include it in the same file as yourView
if you want.Here’s a solution without using UIColor. It’s based on the
blend
extension in @vacawama’s answer.