Skip to content

Instantly share code, notes, and snippets.

@Zeta611
Last active August 3, 2019 20:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Zeta611/92f51c1d03fd4f6247857d364f416da5 to your computer and use it in GitHub Desktop.
Save Zeta611/92f51c1d03fd4f6247857d364f416da5 to your computer and use it in GitHub Desktop.
[UIColor+Extensions] UIColor extensions #extension #iOS
//
// UIColor+Extensions.swift
//
// Created by Jay Lee on 05/05/2019.
// Copyright © 2019 Jay Lee <jaeho.lee@snu.ac.kr>
// This work is free. You can redistribute it and/or modify it under the
// terms of the Do What The Fuck You Want To Public License, Version 2,
// as published by Sam Hocevar. See http://www.wtfpl.net/ for more details.
//
import UIKit
extension UIColor {
convenience init(red: Int, green: Int, blue: Int) {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
convenience init(rgb: Int) {
self.init(
red: (rgb >> 16) & 0xFF,
green: (rgb >> 8) & 0xFF,
blue: rgb & 0xFF
)
}
func lighter(by percentage: CGFloat = 30.0) -> UIColor? {
return adjust(by: abs(percentage))
}
func darker(by percentage: CGFloat = 30.0) -> UIColor? {
return adjust(by: -1 * abs(percentage))
}
func adjust(by percentage: CGFloat = 30.0) -> UIColor? {
var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0
if getRed(&red, green: &green, blue: &blue, alpha: &alpha) {
return UIColor(red: min(red + percentage/100, 1.0),
green: min(green + percentage/100, 1.0),
blue: min(blue + percentage/100, 1.0),
alpha: alpha)
} else {
return nil
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment