Skip to content

Instantly share code, notes, and snippets.

@huntermonk
Last active May 15, 2017 13:56
Show Gist options
  • Save huntermonk/1122a4800f155b496e4e84d3d87e81db to your computer and use it in GitHub Desktop.
Save huntermonk/1122a4800f155b496e4e84d3d87e81db to your computer and use it in GitHub Desktop.
import Foundation
import UIKit
import PlaygroundSupport
extension String {
func toColorIncludingAlpha() -> UIColor? {
var cString: String = self
.trimmingCharacters(in: .whitespacesAndNewlines)
.replacingOccurrences(of: "#", with: "")
guard cString.characters.count == 8 || cString.characters.count == 6 else { return nil }
var rgbValue: UInt32 = 0
Scanner(string: cString).scanHexInt32(&rgbValue)
let blue = CGFloat(rgbValue & 0xff) / 255.0
let green = CGFloat((rgbValue >> 8) & 0xff) / 255.0
let red = CGFloat((rgbValue >> 16) & 0xff) / 255.0
let alpha = cString.characters.count == 6 ? 1 : CGFloat((rgbValue >> 24) & 0xff) / 255.0
return UIColor(red: red, green: green, blue: blue, alpha: alpha)
}
}
private func colorBackground(view: UIView) {
let hex = ["ff48adb6", "ffade13a"]
let colors: [CGColor] = hex.flatMap({ $0.toColorIncludingAlpha() }).map({ $0.cgColor })
let layer = CAGradientLayer()
layer.frame = CGRect(x: 0.0, y: 0.0, width: view.frame.width, height: view.frame.height)
layer.colors = colors
layer.startPoint = CGPoint(x: 0.2, y: 1)
layer.endPoint = CGPoint(x: 0.7, y: -0.6)
// true corner-to-corner
// layer.startPoint = CGPoint(x: 0, y: 1)
// layer.endPoint = CGPoint(x: 1, y: 0)
view.layer.addSublayer(layer)
}
let gradientController = UIViewController()
gradientController.view = UIView(frame: CGRect(x: 50, y: 50, width: 375, height: 667))
gradientController.view.backgroundColor = .blue
colorBackground(view: gradientController.view)
let navigation = UINavigationController(rootViewController: gradientController)
PlaygroundPage.current.liveView = navigation
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment