3
4

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 5 years have passed since last update.

UIViewのグラデーションをstoryboard上で確認する

Last updated at Posted at 2019-02-23

Storyboard上でパラメータをいじっていい感じにグラデーションを確認するクラスを作ってみました
参考にさせてもらったやつにもうちょっとパラメータを追加してみた感じです

こんな感じ

5色まで対応

グラデーションの向きや位置もこんな感じで変えれます

ソース

色を増やしたい場合は colorXlocationXのコンビをコピペってcolorslocationsプロパティの中の配列に足してください
colorclearだとそこは無視されます

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を超絶便利に使う技

3
4
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
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?