Colors and Gradient in SwiftUI
Tags: swiftui, swift, ios, tutorial
Published: 2022-05-11 11:04:56

Colors are powerful. They can convey a message by the visuals and can give a certain kind of vibe to the art (for us, the app). It is one of those inevitable things that you are going to encounter while making pixel perfect production app. So, without further ado, let's dive into colors in SwiftUI. 


## Usage 

The primary usage that most developers encounter first in SwiftUI App Development is as for adding background and color to the view. Let's look into an example:


```swift
  VStack {
            Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce at ante sit amet turpis pretium porta. Cras id dui vel orci scelerisque efficitur et quis dui. Suspendisse tortor nisi, euismod scelerisque sollicitudin in, euismod non ligula. Nulla id risus lobortis nunc venenatis tincidunt. Vestibulum elementum ex est, non sagittis odio dictum eget. Suspendisse non dolor pulvinar, vulputate ligula sit amet, aliquam lorem. Fusce leo ipsum, tempus quis ipsum a, accumsan sagittis justo. Duis placerat, purus vitae ornare semper, enim eros egestas metus, eu euismod arcu ante sed dui. Proin blandit auctor fermentum. Nulla elementum nibh sit amet metus suscipit, eget cursus sapien eleifend. Curabitur tempus mi malesuada quam tempus posuere. Pellentesque ullamcorper tempus dapibus.")
        }
        .padding()
        .foregroundColor(.white)
        .background(Color.blue)
```
Result:

![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dnqecshcyo22s7d7ld3a.jpg)

In the above code, you have [text](https://swiftanytime.com/article/text-swiftui) with a lorem ipsum paragraph in a VStack. Then, `padding()` modifier is added to add some spacing. Then, `foregroundColor` modifier is used to give white foreground text to it. Moreover, `background` modifier is also added to the view to give the particular color as background. 

Note here, you can also use color as a view. 

```Swift 
struct ContentView: View {
    var body: some View {
            Color.red 
    }
}
```
Result: 

![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wtqfz0mfm3h5j1gpy8qs.jpg)


In the above code, you can observe how the `Color.red` acts as a standalone view and takes all the available space. 


## Primary And Secondary Colors 

You can access a few set of colors in SwiftUI but there is a couple of colors that we are going discuss today : Primary and secondary colors. Before understanding it, let's look at a code example:

```Swift
VStack(alignment: .leading, spacing: 20) {
            
            Text("Swift Anytime")
                .bold()
                .font(.title)
                .foregroundColor(.primary)
            
            Text("Think of Swift. Think of Us.")
                .foregroundColor(.secondary)

        }
```
Result: 

![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4otmmi5oje4jxrb1oz34.jpg)

> Note: Color Scheme refers system wide color appearance in apple ecosystem. ie. light mode and dark mode. 

In the above code, you have a VStack with a couple of text: one with primary color as foreground color and second one as secondary color as foreground color. When the system mode is switched, these colors change too. It can be used for coloring the text content so that it's color responds to the system mode change in a well manner. 

## Initializing Colors 


SwiftUI provides with multiple ways to initialize colors. One way to do it is using `Color(red: ..., green: ..., blue: ...)`. You can provide the RGB (Red, Green, blue) value on a 0-1 range.

```Swift
Color(red: 255/255, green: 105/255, blue: 180/255) // Hot Pink Color
```

You can also initialize color with UIColor (from UIKit) and NSColor (from AppKit). Let's try to initialize hot pink with UIColor this time. 

```Swift 
Color(uiColor: UIColor(red: 255/255, green: 105/255, blue: 180/255, alpha: 1))
```

The result of both the initialization given above would be the following: 

![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jtiyiidza2ghcld6fvya.jpg)

## Using Color from Assets folder

You can also add color via Assets folder. For adding a color set, you go to the Assets Folder -> Click "+" button on bottom left corner -> "Add Color Set". 

![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4qn7iq0bbwfxjc2m5m67.gif)

You can customize the color for a particular color scheme or can have the same color for both modes.


![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wrtorrwi08vzv876cljf.gif)


The asset colors can be used in app by `Color("colorName")`. In our example, this color can be used in code by: 

```Swift
Color("SomeColor") 
```

## Opacity 

You can play around with the opacity of the color by using `opacity(...)` modifier where you can enter the opacity between the range of 0 to 1. 

```Swift
       ZStack {
                Color.gray
                    .opacity(0.5) // Setting the color opacity to 0.5 
                Text("Swift Anytime")
                    .foregroundColor(.black)
                    .font(.largeTitle)
                    .bold()
            }
```
Result: 


![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3tev0tkbqj4zi043j6fo.jpg)

	
## Gradients 

SwiftUI provides three type of gradients. Gradients can be used for adding vibrant and bright backgrounds. Let's explore those.

### Linear Gradient 

The simpliest gradient is linear gradient. You can provide the start and end point along with an array of colors. 
	
```Swift
  LinearGradient(colors: [.orange, .red],
                       startPoint: .top,
                       endPoint: .center)
```
	
Result: 
	

![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lju45xeiecz2jw7d5god.jpg)

In the above example, the gradient starts and end at the top and center respectively. Moreover, you can observe that using a correct combination of colors can create a great blend of colors with a very organic gradient.

### Angular Gradients 

Angular Gradients (also called "conic" gradients) are the gradients where the color change is based on the angle. 

```Swift 
  AngularGradient(colors: [.red, .green, .blue, .purple, .pink],
                           center: .center,
                           startAngle: .degrees(90),
                           endAngle: .degrees(360))
```
Result: 

![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r0agxnz89wukfqbihmki.jpg)

In the above code, the angular gradient is initialized with an array of colors, the center of the gradient and the start and end angle. Note here that the start and end angle is added in form of degrees here. But, you can also add it in form of radians by `.radians(...)`. 


## Radial Gradients 

Radial Gradient basically starts adding up the color concentrically from the center point and scales to fit it in the given radius ie. the start and end radius

```Swift
 RadialGradient(colors: [.red, .yellow, .blue, .green],
                       center: .center,
                       startRadius: 20,
                       endRadius: 150)
```
Result: 

![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/la9lnhpw4jjkpbqonq8o.jpg)

You can observe how the colors start to eccentrically get around each other, starting from red and ending it at green, thus, forming a radial gradient.

Congratulations! You deserve to celebrate this moment. Today you learned about colors and its different initilization, setting its opacity and its usage along with different type of gradients. We encourage you to read more related articles till then, have a great time ahead.

Eat. Sleep. Swift Anytime. Repeat.