Skip to content

A color extension library for calculating hex, brightness, etc.

License

Notifications You must be signed in to change notification settings

Kjuly/ColorCalculation

Repository files navigation

ColorCalculation

A color extension library for calculating hex, brightness, etc.


macOS iOS watchOS
SPM CocoaPods Carthage

Installation

See the following subsections for details on the different installation methods.

Color Hex Usage

Create a color from hex value.

// Notes: there's an optional `alpha` arg available.
//   e.g., Color(hex: 0xFFFFFF, alpha: 0.5)
Color(hex: 0xFFFFFF)
UIColor(hex: 0xFFFFFF)
NSColor(hex: 0xFFFFFF)

Or get the hex value from a color.

color.hex
uiColor.hex
nsColor.hex

An extension to String is also provided to get hex values in Int32.

// Below all are valid and returns 0xFFFFFF.
"FFFFFF".toColorHex
"#FFFFFF".toColorHex
"0xFFFFFF".toColorHex

Color Brightness Usage

Get to know a color is bright or dark.

It can be used to determine the color of text on the background. If the background color is bright, use black text color, otherwise use white.

let backgroundColor = UIColor(hex: 0xFFFFFF)
let foregroundColor: UIColor = (backgroundColor.isBrightColor ? .black : .white) 
// `foregroundColor = .black` in this case

Color Conversion Usage

Convenient extension for converting colors between Color, UIColor and NSColor.

color.toUIColor
color.toNSColor

uiColor.toColor
nsColor.toColor