Last active
September 20, 2018 19:52
-
-
Save martinlexow/102f0b0bbb08a4a7ef35031e692f883b to your computer and use it in GitHub Desktop.
This file contains 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
import UIKit | |
class ViewController: UIViewController { | |
@IBOutlet weak var glossyView: GlossyView! | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
} | |
override func viewDidAppear(_ animated: Bool) { | |
self.glossyView.layer.cornerRadius = 16.0 | |
self.glossyView.layer.masksToBounds = true | |
} | |
} | |
class GlossyView: UIView { | |
class MotionDetector: UIInterpolatingMotionEffect { | |
var manipulatedView: GlossyView? = nil | |
override func keyPathsAndRelativeValues(forViewerOffset viewerOffset: UIOffset) -> [String : Any]? { | |
guard let glossyView = self.manipulatedView else { | |
return super.keyPathsAndRelativeValues(forViewerOffset: viewerOffset) | |
} | |
let x = viewerOffset.horizontal | |
let y = viewerOffset.vertical | |
let xPoint = CGPoint(x: x, y: y) | |
let yPoint = CGPoint(x: 0.5, y: 1.0) | |
glossyView.configureGloss(from: xPoint, to: yPoint) | |
return super.keyPathsAndRelativeValues(forViewerOffset: viewerOffset) | |
} | |
} | |
var colors: [CGColor]? = [UIColor.cyan.cgColor, UIColor.blue.cgColor] | |
override func awakeFromNib() { | |
super.awakeFromNib() | |
let detector = MotionDetector() | |
detector.manipulatedView = self | |
self.addMotionEffect(detector) | |
} | |
func configureGloss(from startPoint: CGPoint, to endPoint: CGPoint) { | |
let identifier = "glossy-layer" | |
func createGradient() { | |
let gradient = CAGradientLayer() | |
gradient.name = identifier | |
gradient.frame = self.bounds | |
gradient.startPoint = startPoint | |
gradient.endPoint = endPoint | |
gradient.colors = self.colors | |
self.layer.addSublayer(gradient) | |
} | |
guard let sublayers = self.layer.sublayers else { | |
createGradient() | |
return | |
} | |
if let glossyIndex = sublayers.index(where: { $0.name == identifier }) { | |
if let glossyLayer = sublayers[glossyIndex] as? CAGradientLayer { | |
glossyLayer.startPoint = startPoint | |
glossyLayer.endPoint = endPoint | |
} | |
} else { | |
createGradient() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment