Programmatic Background Gradient Layer

I saw an interesting post about gradient programmatically that was written in Objective-C: https://danielbeard.wordpress.com/2012/02/25/gradient-background-for-uiview-in-ios/

I ported to Swift for my own use and it seems to work fine still!

import Foundation
import QuartzCore
import SpriteKit

class BackgroundLayer
{
    var greyGradient = CAGradientLayer()
    var blueGradient = CAGradientLayer()

    init()
    {
        var colorOne = UIColor(white: 0.9, alpha: 1.0)
        var colorTwo = UIColor(hue: 0.625, saturation: 0.0, brightness: 0.85, alpha: 1.0)
        var colorThree = UIColor(hue: 0.625, saturation: 0.0, brightness: 0.7, alpha: 1.0)
        var colorFour = UIColor(hue: 0.625, saturation: 0.0, brightness: 0.4, alpha: 1.0)
        var colors = [CGColor](arrayLiteral: colorOne.CGColor, colorTwo.CGColor, colorThree.CGColor, colorFour.CGColor)
        println(colors.count)

        var locations = [CGFloat](arrayLiteral: 0.0, 0.02, 0.99, 1.0)

        greyGradient.colors = colors;
        greyGradient.locations = locations;

        var blueColors = [UIColor]()
        blueColors.append(UIColor(red: 120/255.0, green: 135/255.0, blue: 150/255.0, alpha: 1.0))
        blueColors.append(UIColor(red: 57/255.0, green: 79/255.0, blue: 96/255.0, alpha: 1.0))
        var bColors = [CGColor]()
        for color in blueColors
        {
            bColors.append(color.CGColor)
        }
        var bStoppers = [CGFloat](arrayLiteral: 1.0, 1.0)
        blueGradient.colors = bColors
        blueGradient.locations = bStoppers
    }
}
 
24
Kudos
 
24
Kudos

Now read this

Dealing with large numbers in Swift

Type inference is a handy feature in Swift that makes declaring most variables fun and easy. However, there are cases when you must explicitly define the type of the variable. In this example, the starting point is having 4 big numbers,... Continue →