Skip to content

Instantly share code, notes, and snippets.

@nitin-agam
Last active October 4, 2023 06:13
Show Gist options
  • Save nitin-agam/b92bddc265dae556c2c08cb76a960263 to your computer and use it in GitHub Desktop.
Save nitin-agam/b92bddc265dae556c2c08cb76a960263 to your computer and use it in GitHub Desktop.
import UIKit
infix operator |: AdditionPrecedence
public extension UIColor {
struct App {
static let hyperLink = UIColor.colorWithHex(hex: "#FFFFFF")
static let background = UIColor.white | UIColor.black
}
static func | (lightMode: UIColor, darkMode: UIColor) -> UIColor {
guard #available(iOS 13.0, *) else { return lightMode }
return UIColor { (traitCollection) -> UIColor in
return traitCollection.userInterfaceStyle == .light ? lightMode : darkMode
}
}
convenience init(r: Int, g: Int, b: Int) {
assert(r >= 0 && r <= 255, "Invalid red component")
assert(g >= 0 && g <= 255, "Invalid green component")
assert(b >= 0 && b <= 255, "Invalid blue component")
self.init(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: 1.0)
}
class func colorWithHex(hex: String) -> UIColor {
var colorString: String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
// Remove prefix if contain # at 0th position.
if colorString.hasPrefix("#") { colorString.remove(at: colorString.startIndex) }
if colorString.count != 6 { return UIColor.gray }
var rgbValue: UInt64 = 0
Scanner(string: colorString).scanHexInt64(&rgbValue)
return UIColor (
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
class var random: UIColor {
let max = CGFloat(UInt32.max)
let red = CGFloat(arc4random()) / max
let green = CGFloat(arc4random()) / max
let blue = CGFloat(arc4random()) / max
return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
}
class func hexValue(color: UIColor) -> String {
let components = color.cgColor.components
let r: CGFloat = components?[0] ?? 0.0
let g: CGFloat = components?[1] ?? 0.0
let b: CGFloat = components?[2] ?? 0.0
return String.init(format: "#%02lX%02lX%02lX", lroundf(Float(r * 255)), lroundf(Float(g * 255)), lroundf(Float(b * 255)))
}
func lighter(by percentage: CGFloat = 30.0) -> UIColor? {
return self.adjust(by: abs(percentage) )
}
func darker(by percentage: CGFloat = 30.0) -> UIColor? {
return self.adjust(by: -1 * abs(percentage) )
}
private func adjust(by percentage: CGFloat = 30.0) -> UIColor? {
var red:CGFloat = 0, green:CGFloat = 0, blue:CGFloat = 0, alpha:CGFloat = 0
if self.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
}
}
}
@nitin-agam
Copy link
Author

Updated code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment