[iOS]Color gradation and rounding corners

[日本語]

 

I will introduce how to set gradation on a background color of View and round corners of View on iOS.

 

Environment:Xcode 8, Swift 3

 

Use CAGradientLayer to set color gradation to UIView on iOS.

Set gradient colors to CAGradientLayer's colors method and set gradation direction using startPoint and endPoint of CAGradientLayer.

At last, set CAGradientLayer to UIView's layer using insertSublayer.

let buttonSample:UIButton = UIButton()

let gradientLayer = CAGradientLayer()

gradientLayer.frame = buttonSample.bounds

let color1:CGColor = UIColor.blue.cgColor

let color2:CGColor = UIColor.white.cgColor

gradientLayer.colors = [color1, color2]

gradientLayer.startPoint = CGPoint(x: 0, y: 0)

gradientLayer.endPoint = CGPoint(x: 1, y: 1)

buttonSample.layer.insertSublayer(gradientLayer, at: 0)

 

Use cornerRadius of UIView's CALayer for rounding corners of UIView.

buttonSample.layer.cornerRadius = 5

 

[Sample Code]

import UIKit

 

class ViewController: UIViewController {

  let buttonSample:UIButton = UIButton();

 

  override func viewDidLoad() {

    super.viewDidLoad()

    // Do any additional setup after loading the view, typically from a nib.

    buttonSample.frame = CGRect(x: 10, y: 10, width: 100, height: 50)

    buttonSample.setTitle("Sample", for: .normal)

    let gradientLayer = CAGradientLayer()

    gradientLayer.frame = buttonSample.bounds

    let color1:CGColor = UIColor.blue.cgColor

    let color2:CGColor = UIColor.white.cgColor

    gradientLayer.colors = [color1, color2]

    gradientLayer.startPoint = CGPoint(x: 0, y: 0)

    gradientLayer.endPoint = CGPoint(x: 1, y: 1)

    buttonSample.layer.insertSublayer(gradientLayer, at: 0)

    buttonSample.layer.cornerRadius = 5

    self.view.addSubview(buttonSample)

  }

 

  override func didReceiveMemoryWarning() {

    super.didReceiveMemoryWarning()

    // Dispose of any resources that can be recreated.

  }

}