Skip to content

Repository files navigation

Color

VersionBuild StatusSwift VersionCarthage compatible

Color utilities in pure Swift for macOS, iOS, watchOS, and tvOS. Color supports Carthage and Swift Package Manager. It is also tested on Linux.

Color was abstracted from Contrast, a macOS app for checking designs for accessible color combinations.

Installation

Carthage

Add the following to your Cartfile:

github"soffes/Color"

Swift Package Manager

Add the following to your dependencies in your Package.swift:

.package(url:"https://github.com/soffes/Color.git", from:"0.1.1")

Usage

Color provides structs for different color models. Currently only RGB and HSL are supported. Most color calculations are specific to a color model. For example, darkening a color is only available for HSL colors and not RGB colors. If you'd like to darken an RGB color, you’ll need to convert to HSL first. Here’s an example:

letrgb=RGBColor(red:1, green:0, blue:0)lethsl=HSLColor(rgb: rgb)letdarkerRed= hsl.darkening()

Note that Color’s structs don’t support alpha since that isn’t used in any of the color calculations. This may be added in the future.

Hex conversions are only available for RGB colors.

letrgb=RGBColor(hex:"0f0")!
rgb.hex // "00ff00"

NSColor & UIColor

There are convenience methods on NSColor & UIColor if you are working in a Cocoa application. Each color model (RGBColor, HSLColor, etc.) has an extension for SystemColorType which is either NSColor or UIColor depending on the platform. Here's a few examples:

UIColor.red.darkening()UIColor.green.desaturating()NSColor.blue.isDark

WCAG

RGB colors also have WCAG 2.0 calculations. First, calculate a contrast ratio:

letcolor1=RGBColor(red:170.0/255.0, green:204.0/255.0, blue:1)letcolor2=RGBColor(red:34.0/255.0, green:34.0/255.0, blue:51.0/255.0)letcontrastRatio= color1.contrastRatio(to: color2) // 9.51

Now, you can check the conformance level:

ConformanceLevel(contrastRatio: contrastRatio) // .aaa

Thanks

Thanks to color & color-convert for inspiration.

About

Color utilities for macOS, iOS, tvOS, and watchOS

Topics

Resources

Stars

160 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages