0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

グラデーションを作成してみた[Xcode/Storyboard]

Posted at

グラデーションを作ってみたので、忘れないように記事に書いてアウトプットしようと思います。

#環境
・Mac Book Pro(macOS:BigSur)
・Xcode(ver:12.5)

#作成したグラデーション
縦方向
Unknown.gif

横方向
Unknown-1.gif

#コード例

ChangeColorModel.swift
class ChangeColorModel{
    
    func changeColor(topR:CGFloat, topG:CGFloat, topB:CGFloat, topAlpha:CGFloat, bottomR:CGFloat, bottomG:CGFloat, bottomB:CGFloat, bottomAlpha:CGFloat) -> CAGradientLayer{
        let topColor = UIColor(red: topR, green: topG, blue: topB, alpha: topAlpha)
        let bottomColor = UIColor(red: bottomR, green: bottomG, blue: bottomB, alpha: bottomAlpha)
        
        let gradientColor = [topColor.withAlphaComponent(1.0).cgColor, bottomColor.withAlphaComponent(1.0).cgColor]
        
        let gradientLayer = CAGradientLayer()
        gradientLayer.colors = gradientColor
        
        return gradientLayer
    }
ViewController.swift
class ViewController: UIViewController,UITextFieldDelegate {
    
    @IBOutlet weak var btn: UIButton!
    var changeModel = ChangeColorModel()
    var gradientColor = CAGradientLayer()

    override func viewDidLoad() {
        
    }
    
    @IBAction func changeColorAction(_ sender: Any) {
        "色をランダムに設定するためのコード"
        let topRandomR    = CGFloat.random(in: 0.0...1.0)
        let topRandomG    = CGFloat.random(in: 0.0...1.0)
        let topRandomB    = CGFloat.random(in: 0.0...1.0)
        let bottomRandomR = CGFloat.random(in: 0.0...1.0)
        let bottomRandomG = CGFloat.random(in: 0.0...1.0)
        let bottomRandomB = CGFloat.random(in: 0.0...1.0)
    
        gradientColor =  changeModel.changeColor(topR: topRandomR, topG: topRandomG, topB: topRandomB, topAlpha: 1.0, bottomR: bottomRandomR, bottomG: bottomRandomG, bottomB: bottomRandomB, bottomAlpha: 1.0)
        
     "下記の2行を加えると横方向のグラデーションになる"
        gradientColor.startPoint = CGPoint.init(x: 0.0, y: 0.0)
        gradientColor.endPoint = CGPoint.init(x: 1.0, y: 0.0)
        
        gradientColor.frame = self.view.bounds
        self.view.layer.addSublayer(gradientColor)
        btn.layer.zPosition = 1
        
    }
    
}
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?