How to create a color with an alpha value using SwiftUI?

Viewed 28310

In UIKit to create a color with an alpha value there are different ways, for example:

UIColor(red: 0, green: 0, blue: 0, alpha: 0.8)

but this method is not available on the corresponding class Color of SwiftUI.

What can I use?

5 Answers

In SwiftUI there is one specific modifier called opacity that can be use to change the alpha level of any colors

Text("Hello world").background(Color.black.opacity(0.8)) // Set the background color as partially transparent.

Additionally the same modifier can be applied to any view, to change its alpha.

Image("myImage").opacity(0.8) //The image will be partially transparent

The color initializer has an opacity parameter:

Color(red: 1.0, green: 0, blue: 1.0, opacity: 0.2)

Apply the opacity modifier to any SwiftUI View like:

RoundedRectangle(cornerRadius: 5)
    .fill(Color.yellow)
    .frame(width: 50, height: 50)
    .opacity(0.5)

Several answers here point to .opacity() method of View. That covers the most common use cases, but perhaps what the OP wants to know is how to create a Color with transparency.

One is to use Color constructor that has the color space, components and opacity, as in the first example below.

If you already have a Color and want a translucent version of it, use the bridges to UIColor like the second example below

let transparentTeal = Color(.sRGB, red: 0.4, green: 1, blue: 0.1, opacity: 0.2)

let red = Color.red

let transparentRed = Color(UIColor(red).withAlphaComponent(0.3))

It seems that now it is possible to use the .opacity method and still return a Color instead of a View:

Documentation:
func opacity(_ opacity: Double) -> Color
Example:
color.opacity(0.5)
Related