Color
A representation of a color that adapts to a given context.
Declaration
@frozen struct ColorMentioned in
Overview
You can create a color in one of several ways:
Load a color from an Asset Catalog:
let aqua = Color("aqua") // Looks in your app's main bundle by default.Specify component values, like red, green, and blue; hue, saturation, and brightness; or white level:
let skyBlue = Color(red: 0.4627, green: 0.8392, blue: 1.0) let lemonYellow = Color(hue: 0.1639, saturation: 1, brightness: 1) let steelGray = Color(white: 0.4745)Create a color instance from another color, like a UIColor or an NSColor:
#if os(iOS) let linkColor = Color(uiColor: .link) #elseif os(macOS) let linkColor = Color(nsColor: .linkColor) #endifUse one of a palette of predefined colors, like black, green, and purple.
Some view modifiers can take a color as an argument. For example, foregroundStyle(_:) uses the color you provide to set the foreground color for view elements, like text or SF Symbols:
Image(systemName: "leaf.fill")
.foregroundStyle(Color.green)[Image]
Because SwiftUI treats colors as View instances, you can also directly add them to a view hierarchy. For example, you can layer a rectangle beneath a sun image using colors defined above:
ZStack {
skyBlue
Image(systemName: "sun.max.fill")
.foregroundStyle(lemonYellow)
}
.frame(width: 200, height: 100)A color used as a view expands to fill all the space it’s given, as defined by the frame of the enclosing ZStack in the above example:
[Image]
SwiftUI only resolves a color to a concrete value just before using it in a given environment. This enables a context-dependent appearance for system defined colors, or those that you load from an Asset Catalog. For example, a color can have distinct light and dark variants that the system chooses from at render time.
Topics
Creating a color
Creating a color from component values
init(hue:saturation:brightness:opacity:)init(_:white:opacity:)init(_:red:green:blue:opacity:)Color.RGBColorSpace