Skip to content

Instantly share code, notes, and snippets.

@codyrobb
Created May 9, 2016 21:51
Show Gist options
  • Save codyrobb/8f25de805326c269882b8079f70d93e4 to your computer and use it in GitHub Desktop.
Save codyrobb/8f25de805326c269882b8079f70d93e4 to your computer and use it in GitHub Desktop.
//
// GradientView.swift
// Notion
//
// Created by Cody Robertson on 3/16/16.
// Copyright © 2016 Lift, Inc. All rights reserved.
//
import Foundation
import UIKit
class GradientView: UIView {
// MARK: -
enum GradientType {
case Linear
case Radial
}
// MARK: -
// MARK: Public Properties
var type: GradientType {
didSet {
setNeedsDisplay()
layoutIfNeeded()
}
}
var colors: [UIColor] {
didSet {
setNeedsDisplay()
layoutIfNeeded()
}
}
// MARK: -
// MARK: Private Properties
private var locations: [CGFloat] {
return colors
.enumerate()
.map { (index, element) in
return (1.0 / CGFloat(colors.count - 1)) * CGFloat(index)
}
}
private var components: [CGFloat] {
return colors
.map {
let components = CGColorGetComponents($0.CGColor)
let colorComponents = Array(count: 4, repeatedValue: 0.0)
return colorComponents
.enumerate()
.map { (index, element) in components[index] }
}
.reduce([], combine: +)
}
// MARK: -
// MARK: Initialization
init(type: GradientType, colors: [UIColor]) {
self.type = type
self.colors = colors
super.init(frame: CGRectZero)
}
required init?(coder aDecoder: NSCoder) {
fatalError("Use init(colors:) instead.")
}
// MARK: -
// MARK: Methods
override func drawRect(rect: CGRect) {
guard colors.count > 0 else { return }
let context = UIGraphicsGetCurrentContext()
let colorspace = CGColorSpaceCreateDeviceRGB()
let gradient = CGGradientCreateWithColorComponents(colorspace, components, locations, locations.count)
switch type {
case .Linear:
let start = CGPoint(x: rect.midX, y: 0)
let end = CGPoint(x: rect.midX, y: rect.maxY)
CGContextDrawLinearGradient(context, gradient, start, end, .DrawsAfterEndLocation)
case .Radial:
let center = CGPoint(x: rect.midX, y: rect.midY)
let radius = max(rect.midX, rect.midY) * 0.75
CGContextDrawRadialGradient(context, gradient, center, 0, center, radius, .DrawsAfterEndLocation)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment