1
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.

【Swift】グラデーションのフィルターをかける

Posted at

3行で

  • グラデーション用のクラスを作る
  • グラデーション用のクラスを読み込む
  • グラデーション用のクラスに値を渡す

色設定のクラスを作る

今回は別でクラスを作る。
ページによって色を変えたいときなどはこっちのほうがつぶしが効くし、可読性もあがる(レビュアーに叱られない)。

ChangeColor.swift
import Foundation
import UIKit

class ChangeColor {
  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.cgColor, bottomColor.cgColor]
    let gradientLayer = CAGradientLayer()
    gradientLayer.colors = gradientColor
    
    return gradientLayer
  }
}

色設定のクラスに値を渡す

ViewController.swift
class ViewController: UIViewController {

  // 色設定のクラスをインスタンス化する
  var changeColor = ChangeColor()
  var gradientLayer = CAGradientLayer()
  
  override func viewDidLoad() {
    super.viewDidLoad()
     
    // 色設定のクラスに値を渡す
    gradientLayer = changeColor.changeColor(topR: 0.07, topG: 0.13, topB: 0.26, topAlpha: 1.0, bottomR: 0.54, bottomG: 0.74, bottomB: 0.74, bottomAlpha: 1.0)
    // boundsは全体を表す
    gradientLayer.frame = view.bounds
    
    view.layer.insertSublayer(gradientLayer, at: 0)
  }
}

ところで『インスタンス化する』ってなんなんだろう?
漠然と使っている。

1
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
1
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?