Learning how to add Gradients in iOS

in #utopian-io8 years ago (edited)

How to use CAGRadientLayer to make gradients in iOS?

Hi today i am going to teach you something we call Gradients in iOS. We all wants our app to look better in colors, designs and this can be achieved by using UIKit class CAGradientLayer which is a subclass of CALayer.

What you will learn

  • You will learn how to use CAGradientLayer class to show bunch of colors mixed together.
  • You will learn how to add simple CABasicAnimation on layer to change colors at runtime.

Requirements

  • Mac
  • Xcode
  • Knowledge of programming in Swift language.

Difficulty

  • Basic

Tutorial Contents

1. Simple Mixing of colors.

The CAGradientLayer class exists on the top CALayer and is used to make gradient effects. You can generate a simple gradient using just few lines of code but to make it more attractive some of it's properties can be very useful as they all are animatable.

So Let's start with making your first app and make it look beautiful using gradients.

Open Xcode and create a project with single view application. The project contains the AppDelegate class which is the subclass of the UIApplication class and is the entry point of the application.
Go to ViewController.swift class and declare a variable as

var gradientLayer: CAGradientLayer!

now we create a function named createSimpleGradientLAyer that will render the gradient layer on the layer property of the view.

func createSimpleGradientLAyer() {
    gradientLayer = CAGradientLayer()
    gradientLayer.frame = self.view.bounds
    gradientLayer.colors = [UIColor.red.cgColor, UIColor.green.cgColor, UIColor.black.cgColor]
    self.view.layer.addSublayer(gradientLayer)
}

this function just initialise the gradientLayer object and give it frames of the target layer. With colors property you can assign the array of colors that will be used to fill it. so here we used three colors red, green and black and in final statement we have added the gradient layer on the view's layer property.

Now we can call this method in ViewWillAppear method.

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    self.createSimpleGradientLayer()
}

Run you XCode project and your screen will look something like this(see image below).

Simulator Screen Shot - iPhone SE - 2018-03-27 at 09.30.59.png![ezgif.com-crop.gif]

  1. Color Animation

In this part i will teach you how to change colors with animation using class CABasicAnimation and adding it on gradient layer.

first we will define two properties as
var colorSets = [CGColor]
var currentColorSet: Int!

and now create a simple set of colors as

func createColorSets() {
colorSets.append([UIColor.red.cgColor, UIColor.blue.cgColor])
colorSets.append([UIColor.green.cgColor, UIColor.magenta.cgColor])
colorSets.append([UIColor.init(red: 91, green: 177, blue: 227, alpha: 1.0).cgColor, UIColor.init(red: 102, green: 42, blue: 133, alpha: 1.0).cgColor])

    currentColorSet = 0
}

we sill call this createColorSets method in viewDidLoad and will add a simple UITapGesture on view as
in ViewDidLoad method

let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.handleTapGesture(gestureRecognizer:)))
self.view.addGestureRecognizer(tapGestureRecognizer)

now we will create handleTapGesture method and do some animation in it

func handleTapGesture(gestureRecognizer: UITapGestureRecognizer) {
if currentColorSet < colorSets.count - 1 {
currentColorSet! += 1
}
else {
currentColorSet = 0
}

    let colorAnimation = CABasicAnimation(keyPath: "colors")
    colorAnimation.duration = 2.0
    colorAnimation.toValue = colorSets[currentColorSet]
    colorAnimation.fillMode = kCAFillModeForwards
    colorAnimation.isRemovedOnCompletion = false
    gradientLayer.add(colorAnimation, forKey: "colorChange")
    colorAnimation.delegate = self
    gradientLayer.add(colorAnimation, forKey: "colorChange")
}

this function jus check currentColorSet if it is in the colorSets bounds then we will inreament it by one onter wise we will set it to 0.

Now we create CABasicAnimation object with keypath "colors" and give it animation duration as 2.0. Set its toValue property to the set of colors we just created and its fill mode as kCAFillModeForwards, we will not remove animation once it is completed, so set its isRemovedOnCompletion property to false.

Now we add this animation on gradient layer and for keyPath "colorChange". Assign the degelates of CAAnimation to self and do not forget confirm to protocol CAAnimationDelegate.

Now we will implement the delegate as

func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
if flag {
gradientLayer.colors = colorSets[currentColorSet]
}
}
which will set the gradientLayer colors to the current set of colors after the animation completes.

Now run the project and the color change animation will look something like this :-



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Your contribution cannot be approved because it does not follow the Utopian Rules.

A submission may be rejected if the moderator provides a link to a superior tutorial on the same subject.

Thank you for your contribution but there are already similar tutorial in appcoda.com

https://www.appcoda.com/cagradientlayer/

You can contact us on Discord.
[utopian-moderator]

Hey @dakeshi, I just gave you a tip for your hard work on moderation. Upvote this comment to support the utopian moderators and increase your future rewards!

Coin Marketplace

STEEM 0.04
TRX 0.33
JST 0.100
BTC 64685.76
ETH 1872.76
USDT 1.00
SBD 0.38