-
-
Save sendoa/691c8fc4c16b6b78c3cedb8dddecb2d6 to your computer and use it in GitHub Desktop.
Snippet of the Week: Lighter and Darker Colors
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 | |
import PlaygroundSupport | |
public extension UIColor { | |
public func hsba() -> (hue: CGFloat, saturation: CGFloat, brightness: CGFloat, alpha: CGFloat)? { | |
var hue: CGFloat = .nan, saturation: CGFloat = .nan, brightness: CGFloat = .nan, alpha: CGFloat = .nan | |
guard self.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) else { | |
return nil | |
} | |
return (hue: hue, saturation: saturation, brightness: brightness, alpha: alpha) | |
} | |
public func changedBrightness(byPercentage perc: CGFloat) -> UIColor? { | |
if perc == 0 { | |
return self.copy() as? UIColor | |
} | |
guard let hsba = hsba() else { | |
return nil | |
} | |
let percentage: CGFloat = min(max(perc, -1), 1) | |
let newBrightness = min(max(hsba.brightness + percentage, -1), 1) | |
return UIColor(hue: hsba.hue, saturation: hsba.saturation, brightness: newBrightness, alpha: hsba.alpha) | |
} | |
public func lightened(byPercentage percentage: CGFloat = 0.1) -> UIColor? { | |
return changedBrightness(byPercentage: percentage) | |
} | |
public func darkened(byPercentage percentage: CGFloat = 0.1) -> UIColor? { | |
return changedBrightness(byPercentage: -percentage) | |
} | |
public func changedSaturation(byPercentage perc: CGFloat) -> UIColor? { | |
if perc == 0 { | |
return self.copy() as? UIColor | |
} | |
guard let hsba = hsba() else { | |
return nil | |
} | |
let percentage: CGFloat = min(max(perc, -1), 1) | |
let newSaturation = min(max(hsba.saturation + percentage, -1), 1) | |
return UIColor(hue: hsba.hue, saturation: newSaturation, brightness: hsba.brightness, alpha: hsba.alpha) | |
} | |
public func tinted(byPercentage percentage: CGFloat = 0.1) -> UIColor? { | |
return changedSaturation(byPercentage: percentage) | |
} | |
public func shaded(byPercentage percentage: CGFloat = 0.1) -> UIColor? { | |
return changedSaturation(byPercentage: -percentage) | |
} | |
} | |
let stackView1 = UIStackView(frame: CGRect(x: 0, y: 0, width: 500, height: 200)) | |
stackView1.axis = .horizontal | |
stackView1.distribution = .fillEqually | |
var views1: [UIView] = [] | |
let color1 = UIColor.purple.darkened(byPercentage: 0.2)! | |
for i in 0...4 { | |
let subcolor = color1.lightened(byPercentage: CGFloat(i) * 0.1) | |
let subview = UIView(frame: CGRect(x: 1, y: 1, width: 1, height: 1)) | |
subview.backgroundColor = subcolor | |
views1 += [subview] | |
stackView1.addArrangedSubview(subview) | |
} | |
PlaygroundPage.current.liveView = stackView1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment