Storyboard上でパラメータをいじっていい感じにグラデーションを確認するクラスを作ってみました
参考にさせてもらったやつにもうちょっとパラメータを追加してみた感じです
こんな感じ
5色まで対応
ソース
色を増やしたい場合は colorX
とlocationX
のコンビをコピペってcolors
とlocations
プロパティの中の配列に足してください
color
がclear
だとそこは無視されます
GradationView.swift
import UIKit
@IBDesignable
class GradationView: UIView {
var gradientLayer: CAGradientLayer?
@IBInspectable var color1: UIColor = UIColor.white {didSet {self.setNeedsLayout()}}
@IBInspectable var location1: Float = 0 {didSet {self.setNeedsLayout()}}
@IBInspectable var color2: UIColor = UIColor.black {didSet {self.setNeedsLayout()}}
@IBInspectable var location2: Float = 0 {didSet {self.setNeedsLayout()}}
@IBInspectable var color3: UIColor = UIColor.clear {didSet {self.setNeedsLayout()}}
@IBInspectable var location3: Float = 0 {didSet {self.setNeedsLayout()}}
@IBInspectable var color4: UIColor = UIColor.clear {didSet {self.setNeedsLayout()}}
@IBInspectable var location4: Float = 0 {didSet {self.setNeedsLayout()}}
@IBInspectable var color5: UIColor = UIColor.clear {didSet {self.setNeedsLayout()}}
@IBInspectable var location5: Float = 0 {didSet {self.setNeedsLayout()}}
@IBInspectable var startPoint: CGPoint = CGPoint(x: 0.5, y: 0.0) {didSet {self.setNeedsLayout()}}
@IBInspectable var endPoint: CGPoint = CGPoint(x: 0.5, y: 1.0) {didSet {self.setNeedsLayout()}}
private var locations:[NSNumber]{
return [location1, location2, location3, location4, location5].enumerated().filter{colors.count-1 > $0.offset}.map{NSNumber(value: $0.element)}
}
private var colors:[CGColor]{
return [color1, color2, color3, color4, color5].filter{$0 != .clear}.map{$0.cgColor}
}
override func layoutSubviews() {
super.layoutSubviews()
setGradation()
}
private func setGradation() {
gradientLayer?.removeFromSuperlayer()
gradientLayer = CAGradientLayer()
gradientLayer!.startPoint = startPoint
gradientLayer!.endPoint = endPoint
gradientLayer!.colors = colors
gradientLayer!.locations = locations
gradientLayer!.frame.size = frame.size
layer.addSublayer(gradientLayer!)
layer.masksToBounds = true
}
}
参考
[Swift]UIViewのグラデーションをstoryBoard上で確認する
Swift CAGradientLayer でグラデーションの色や方向を指定する方法
StoryboardやNibを超絶便利に使う技