
環境:Xcode 8, Swift 3
iOSでUIViewのグラデーションを設定する場合はCAGradientLayerを使用します。
CAGradientLayerのcolorsメソッドにグラデーションに使用する色を配列として設定し、CAGradientLayerのstartPointとendPointでグラデーションの方向を定義します。
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)
iOSでUIViewの角を丸くするときにはUIViewのCALayerのcornerRadiusを使用します。
buttonSample.layer.cornerRadius = 5
[サンプル全文]
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.
}
}
Write a comment