Created
July 6, 2020 21:40
-
-
Save BrunoScheltzke/58318371e4a4c3b0d4d7ced5c8208d1a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// GradientView.swift | |
// | |
// Created by Bruno Scheltzke on 19/06/20. | |
// Copyright © 2020 Bruno Scheltzke All rights reserved. | |
// | |
import UIKit | |
@IBDesignable | |
class GradientView: UIView { | |
@IBInspectable var startColor: UIColor = .black { didSet { updateColors() }} | |
@IBInspectable var endColor: UIColor = .white { didSet { updateColors() }} | |
@IBInspectable var startLocation: Double = 0.05 { didSet { updateLocations() }} | |
@IBInspectable var endLocation: Double = 0.95 { didSet { updateLocations() }} | |
@IBInspectable var horizontalMode: Bool = false { didSet { updatePoints() }} | |
@IBInspectable var diagonalMode: Bool = false { didSet { updatePoints() }} | |
override class var layerClass: AnyClass { return CAGradientLayer.self } | |
var gradientLayer: CAGradientLayer { return layer as! CAGradientLayer } | |
func updatePoints() { | |
if horizontalMode { | |
gradientLayer.startPoint = diagonalMode ? CGPoint(x: 1, y: 0) : CGPoint(x: 0, y: 0.5) | |
gradientLayer.endPoint = diagonalMode ? CGPoint(x: 0, y: 1) : CGPoint(x: 1, y: 0.5) | |
} else { | |
gradientLayer.startPoint = diagonalMode ? CGPoint(x: 0, y: 0) : CGPoint(x: 0.5, y: 0) | |
gradientLayer.endPoint = diagonalMode ? CGPoint(x: 1, y: 1) : CGPoint(x: 0.5, y: 1) | |
} | |
} | |
func updateLocations() { | |
gradientLayer.locations = [startLocation as NSNumber, endLocation as NSNumber] | |
} | |
func updateColors() { | |
gradientLayer.colors = [startColor.cgColor, endColor.cgColor] | |
} | |
override func layoutSubviews() { | |
super.layoutSubviews() | |
updatePoints() | |
updateLocations() | |
updateColors() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment