Yet another extension to manipulate colors easily in Swift and SwiftUI

Overview

DynamicColor

Supported Platforms Version Carthage compatible Swift Package Manager compatible Build status

DynamicColor provides powerful methods to manipulate colors in an easy way in Swift and SwiftUI.

example screenshot example screenshot

RequirementsUsageInstallationContributionContactLicense

Requirements

  • iOS 11.0+ / Mac OS X 10.11+ / tvOS 11.0+ / watchOS 4.0+
  • Xcode 10.2+
  • Swift 5.0+

Usage

Creation (Hex String)

Firstly, DynamicColor provides useful initializers to create colors using hex strings or values:

let color = UIColor(hexString: "#3498db")
// equivalent to
// color = UIColor(hex: 0x3498db)

To be platform independent, the typealias DynamicColor can also be used:

let color = DynamicColor(hex: 0x3498db)
// On iOS, WatchOS or tvOS, equivalent to
// color = UIColor(hex: 0x3498db)
// On OSX, equivalent to
// color = NSColor(hex: 0x3498db)

You can also retrieve the RGBA value and components very easily using multiple methods like toHexString, toHex, toRGBA, etc.

SwiftUI

From the v5, DynamicColor also support basic methods to create and manipulate colors with SwiftUI.

let color = Color(hex: 0x3498db)

Darken & Lighten

These two create a new color by adjusting the lightness of the receiver. You have to use a value between 0 and 1.

lighten and darken color

let originalColor = DynamicColor(hexString: "#c0392b")

let lighterColor = originalColor.lighter()
// equivalent to
// lighterColor = originalColor.lighter(amount: 0.2)

let darkerColor = originalColor.darkened()
// equivalent to
// darkerColor = originalColor.darkened(amount: 0.2)

Saturate, Desaturate & Grayscale

These will adjust the saturation of the color object, much like darkened and lighter adjusted the lightness. Again, you need to use a value between 0 and 1.

saturate, desaturate and grayscale color

let originalColor = DynamicColor(hexString: "#c0392b")

let saturatedColor = originalColor.saturated()
// equivalent to
// saturatedColor = originalColor.saturated(amount: 0.2)

let desaturatedColor = originalColor.desaturated()
// equivalent to
// desaturatedColor = originalColor.desaturated(amount: 0.2)

// equivalent to
// let grayscaledColor = originalColor.grayscaled(mode: .luminance)
let grayscaledColor = originalColor.grayscaled()

let grayscaledColorLuminance = originalColor.grayscaled(mode: .luminance)
let grayscaledColorLightness = originalColor.grayscaled(mode: .lightness)
let grayscaledColorAverage = originalColor.grayscaled(mode: .average)
let grayscaledColorValue = originalColor.grayscaled(mode: .value)

Adjust-hue & Complement

These adjust the hue value of the color in the same way like the others do. Again, it takes a value between 0 and 1 to update the value.

ajusted-hue and complement color

let originalColor = DynamicColor(hex: 0xc0392b)

// Hue values are in degrees
let adjustHueColor = originalColor.adjustedHue(amount: 45)

let complementedColor = originalColor.complemented()

Tint & Shade

A tint is the mixture of a color with white and a shade is the mixture of a color with black. Again, it takes a value between 0 and 1 to update the value.

tint and shade color

let originalColor = DynamicColor(hexString: "#c0392b")

let tintedColor = originalColor.tinted()
// equivalent to
// tintedColor = originalColor.tinted(amount: 0.2)

let shadedColor = originalColor.shaded()
// equivalent to
// shadedColor = originalColor.shaded(amount: 0.2)

Invert

This can invert the color object. The red, green, and blue values are inverted, while the opacity is left alone.

invert color

let originalColor = DynamicColor(hexString: "#c0392b")

let invertedColor = originalColor.inverted()

Mix

This can mix a given color with the receiver. It takes the average of each of the RGB components, optionally weighted by the given percentage (value between 0 and 1).

mix color

let originalColor = DynamicColor(hexString: "#c0392b")

let mixedColor = originalColor.mixed(withColor: .blue)
// equivalent to
// mixedColor = originalColor.mixed(withColor: .blue, weight: 0.5)
// or
// mixedColor = originalColor.mixed(withColor: .blue, weight: 0.5, inColorSpace: .rgb)

Gradients

DynamicColor provides an useful object to work with gradients: DynamicGradient. It'll allow you to pick color from gradients, or to build a palette using different color spaces (.e.g.: RGB, HSL, HSB, Cie L*a*b*).

Let's define our reference colors and the gradient object:

let blue   = UIColor(hexString: "#3498db")
let red    = UIColor(hexString: "#e74c3c")
let yellow = UIColor(hexString: "#f1c40f")

let gradient = DynamicGradient(colors: [blue, red, yellow])
// equivalent to
// let gradient = [blue, red, yellow].gradient
RGB

Let's build the RGB palette (the default color space) with 8 colors:

RGB gradient

let rgbPalette = gradient.colorPalette(amount: 8)
HSL

Now if you want to change the gradient color space to have a different effect, just write the following lines:

HSL gradient

let hslPalette = gradient.colorPalette(amount: 8, inColorSpace: .hsl)
Cie L*a*b*

Or if you prefer to work directly with array of colors, you can:

Cie L*a*b* gradient

let labPalette = [blue, red, yellow].gradient.colorPalette(amount: 8, inColorSpace: .lab)

And many more...

DynamicColor also provides many another useful methods to manipulate the colors like hex strings, color components, color spaces, etc. To go further, take a look at the example project.

Installation

CocoaPods

Install CocoaPods if not already available:

$ [sudo] gem install cocoapods
$ pod setup

Go to the directory of your Xcode project, and Create and Edit your Podfile and add DynamicColor:

$ cd /path/to/MyProject
$ touch Podfile
$ edit Podfile
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'

use_frameworks!
pod 'DynamicColor', '~> 5.0.0'

Install into your project:

$ pod install

Open your project in Xcode from the .xcworkspace file (not the usual project file):

$ open MyProject.xcworkspace

You can now import DynamicColor framework into your files.

Carthage

Carthage is a decentralized dependency manager that automates the process of adding frameworks to your Cocoa application.

You can install Carthage with Homebrew using the following command:

$ brew update
$ brew install carthage

To integrate DynamicColor into your Xcode project using Carthage, specify it in your Cartfile file:

github "yannickl/DynamicColor" >= 5.0.0

Swift Package Manager

You can use The Swift Package Manager to install DynamicColor by adding the proper description to your Package.swift file:

import PackageDescription

let package = Package(
    name: "YOUR_PROJECT_NAME",
    targets: [],
    dependencies: [
        .package(url: "https://github.com/yannickl/DynamicColor.git", from: "5.0.0")
    ]
)

Note that the Swift Package Manager is still in early design and development, for more information checkout its GitHub Page.

Manually

Download the project and copy the DynamicColor folder into your project to use it in.

Contribution

Contributions are welcomed and encouraged .

Contact

Yannick Loriot

License (MIT)

Copyright (c) 2015-present - Yannick Loriot

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Comments
  • Failed to verify bitcode issue

    Failed to verify bitcode issue

    I get the following error message while trying to do an Ad-Hoc export of project that uses DynamicColor framework:

    Failed to verify bitcode in DynamicColor.framework/DynamicColor:
    
    description = "Failed to verify bitcode in DynamicColor.framework/DynamicColor:\nerror: Cannot extract bundle
    level = ERROR;
    type = "malformed-payload";
    

    It happens in Compile Bitcode expert step.

    opened by damirstuhec 8
  • Add Swiftlint

    Add Swiftlint

    Hey,

    As discussed in #28, here is an implementation of Swiftlint:

    • SwiftLint runs on each sample project build (so you can see mistakes directly when coding)
    • SwifLint is launched by Travis. So, if there is a major issue, it will break the build.
    • I fixed some issues
    • But lots of issues have been fixed by swiftlint autocorrect.

    Note that swiftlint only check files in ./Sources. If you want to see results of lint into Xcode, you just have to install SwiftLint: brew install swiftlint

    opened by jlnquere 5
  • Fatal error: Not enough bits to represent the passed value

    Fatal error: Not enough bits to represent the passed value

    Describe the bug We got a crash on an iPhone 5C running iOS 10.3.3 and it's triggered by this line:

    UIColor(hex: 0xffffff80, useAlpha: true)
    

    The crash happens on line 87 in DynamicColor.swift since Int is the same size as Int32 on 32 bit platforms.

    To Reproduce Steps to reproduce the behavior:

    1. Add the line above to a project
    2. Run it on an iPhone 5 using iOS 10.x in a simulator
    3. See crash

    Expected behavior To not crash. :)

    Smartphone (please complete the following information):

    • Device: 32 bit devices, i.e. iPhone 5C
    • OS: 10.3

    Additional context

    opened by leogiertz 4
  • Gradient colors

    Gradient colors

    It would be nice to have a method that generates color on a gradient between two colors. API might look like that:

    red.gradientTo(green).colorAt(0.5) // yellow-ish
    
    enhancement 
    opened by nubbel 4
  • Manipulate alpha component of color

    Manipulate alpha component of color

    How about a convenience function for manipulating the alpha component of a color? It seems like you can manipulate just about every other aspect of the color, except that.

    If there's already an easy way to do this that I have missed?

    opened by andreasmpet 3
  • Fixing a problem building in release modes

    Fixing a problem building in release modes

    The version 5.0.0 wont build in release mode -see https://github.com/yannickl/DynamicColor/issues/59 - this PR fixes that by updating some iOS deployment versions: from 8.0 to 11.0.

    opened by richardgroves 2
  • Add support for grayscale modes

    Add support for grayscale modes

    The current implementation of final func grayscaled() -> DynamicColor uses the HSL lightness as as measurement of lightness.

    While this is computationally convenient it does not provide a good match for the human perception of lightness.

    Relative luminance (the Y in XYZ) provides a much more accurate measure.

    This PR adds support for specifying which color space (i.e. xyz, hsl, rgb, hsv) to be used for grayscaling, defaulting to .lightness (aka HSL) for the sake of not introducing a breaking-change.

    ⚠️ Depends on https://github.com/yannickl/DynamicColor/pull/56

    opened by regexident 2
  • Update SPM syntax with 4.2.1

    Update SPM syntax with 4.2.1

    Summary

    The syntax for installing the package via Swift Package Manager has changed since README.md was created. This PR is to update the syntax along with the latest release version number* "4.2.1".

    * as of Wednesday, 2 October 2019

    opened by landtanin 2
  • toRGBA()

    toRGBA()

    extension DynamicColor {
        func toRGBA() -> UInt32 {
            func roundToHex(_ x: CGFloat) -> UInt32 {
                guard x > 0 else { return 0 }
                let rounded: CGFloat = round(x * 255)
                return UInt32(rounded)
            }
            let rgba = toRGBAComponents()
            return roundToHex(rgba.a) << 24 | roundToHex(rgba.b) << 16 | roundToHex(rgba.g) << 8 | roundToHex(rgba.r)
        }
    }
    

    I use this method when working low level with images raw data buffers, maybe could be added ?

    opened by nferruzzi 2
  • Fixes crash on iPhone 5

    Fixes crash on iPhone 5

    I had this crash on iPhone 5 (and probably on other 32bit devices):

    When I called this method with the value 4290756543 or rgb = (r = 0.75, g = 0.75, b = 0.75, a = 1) it crashed saying Not enough bits to represent a signed value on line 86.

    This fixes it, but please review my code to warn me if there's any mistake

    opened by puelocesar 2
  • hex should support the alpha channel

    hex should support the alpha channel

    Thanks for the library! I saw that currently alpha is always set to FF, which limits its usefulness. Could you update so that alpha value could also be supported? e.g. when the hex has 8 digits, use the last 2 as alpha, if the hex has 6 digits, default to FF

    opened by hyouuu 2
  • Full Colorspace + Platform Support

    Full Colorspace + Platform Support

    Is your feature request related to a problem? Please describe. No

    Describe the solution you'd like Support for:

    1. HSV
    2. Lab
    3. Luv
    4. Yxy
    5. CMY
    6. CMYK
    7. Grayscale

    Describe alternatives you've considered

    • https://github.com/dylan/colors
    • https://github.com/timrwood/ColorSpaces

    Additional context

    • I think this library should be for all Apple platforms and contain all different color spaces available on Apple devices.
    opened by raymondwelch33 0
  • Incorrect gradients

    Incorrect gradients

    Trying to make a simple gradient between red #ff0000 and blu #0000ff with color spaces HSL and HSB I have an unexpected result. It seem works correctly with RGB and L*a*b*.

    Expected behavior should be similar to RGB and L*a*b* spaces.

    Additional considerations:

    • For HSL color space, increasing the steps the gradient seems to make the opposite turn of the wheel instead of the shortest way.
    • For HSB I cannot understand which way is used.

    Maybe this func could have a bug: mixedHue(source: CGFloat, target: CGFloat) in DynamicColor+Mixing.swift

    hsl hsb lab rgb
    opened by gmcusaro 0
  • Can not build in simulator on mac m1 device

    Can not build in simulator on mac m1 device

    It is working fine on device but when i run for simulator on my m1 device it gives me this error. Could not find module 'DynamicColor' for target 'x86_64-apple-ios-simulator'; found: arm64, arm64-apple-ios-simulator

    opened by siam009 2
  • Shape Style?

    Shape Style?

    Hi,

    I've got this code:

    VStack {
    						Text("Active Window Border")
    						ColorPickerRing(color: $activeWindowBorderColor, strokeWidth: 30)
    							.frame(width: 100, height: 100, alignment: .center)
    						HStack {
    							Button("Cancel") {
    								// somehow reset color
    								self.colorPicker = false
    								
    							}
    							Button("OK") {
    								self.colorPicker = false
    							}
    							RoundedRectangle(cornerRadius: 5.0)
    								.fill(activeWindowBorderColor)
    						}
    					}.frame(width: 350, height: 350, alignment: .center)
    
    

    That throws: Instance method 'fill(_:style:)' requires that 'DynamicColor' (aka 'NSColor') conform to 'ShapeStyle'

    But when I user Color.white it works.

    Can anybody explain that thing with ShapeStyle?

    opened by 24unix 0
  • Version 5.0 was not found using pod

    Version 5.0 was not found using pod

    Describe the bug I updated repo to the latest and found that the latest version of DynamicColor was 4.2.0, but the latest version 5.0 could not be found

    To Reproduce Steps to reproduce the behavior:

    1. open the 'terminal'
    2. input 'pod repo update'
    3. and input 'pod search DynamicColor'
    4. See the latest version was 4.2.0
    opened by lzzhoujielun 3
  • Broken release builds – misconfigured SwiftUI dependency

    Broken release builds – misconfigured SwiftUI dependency

    Describe the bug Since v5.0.0 DynamicColor.framework does not build in release, so breaking release build of host apps. Reproducible in your own demo app.

    To Reproduce Steps to reproduce the behavior:

    1. Open DynamicColorExample.xcodeproj in Xcode 11.3
    2. Select target iOSExample + Generic iOS Device
    3. Build
    4. Build of DynamicColor.framework fails with error:
    ~/Dev/External/Graphics/DynamicColor/Sources/SwiftUIColor.swift:30:18: error: use of undeclared type 'Color'
    public extension Color {
    

    Expected behavior build does not fail

    Smartphone (please complete the following information): any

    Additional context Suspect this is because the framework is not declaring correct dependency on SwiftUI.framework - needs to be added as optional linked framework. This is problematic for projects that do not want to introduce dependency on SwiftUI. Would also help if you could split your podspec into a basic that excludes SwiftUIColor.swift and a subspec that adds it for those who need it; still leaves Carthage users in a bind. Alternatively, duplicate your targets to provide with & without SwiftUI versions of the frameworks. (No plans here to adopt SwiftUI until its well past version 2.)

    opened by t0rst 10
Owner
Yannick Loriot
iOS developer and nodejs addict. Open-source lover and technology enthusiast.
Yannick Loriot
A pure Swift library that allows you to easily convert SwiftUI Colors to Hex String and vice versa.

iOS · macOS · watchOS · tvOS A pure Swift library that allows you to easily convert SwiftUI Colors to Hex String and vice versa. There is also support

Novem 3 Nov 20, 2022
All wikipedia colors implemented as easy to use UIColor extension 🌈

UIColor-WikiColors All wikipedia colors implemented as an easy to use UIColor extension. Have you ever tried using UIColor.lightBlue just to be welcom

Szymon Maślanka 58 Jul 30, 2022
A beautiful set of predefined colors and a set of color methods to make your iOS/OSX development life easier.

Installation Drag the included Colours.h and Colours.m files into your project. They are located in the top-level directory. You can see a demo of how

Ben Gordon 3.1k Dec 28, 2022
ColorKit makes it easy to find the dominant colors of an image

ColorKit is your companion to work with colors on iOS. Features Installation Sample Project Contributing License Features Dominant Colors Col

Boris Emorine 569 Dec 29, 2022
Manage Colors, Integrate Night/Multiple Themes. (Unmaintained)

Easily integrate and high performance Providing UIKit and CoreAnimation category Read colour customisation from file Support different themes Generate

Draven 3.6k Dec 15, 2022
Save the color of your moments. Remember your moments with colors you name.🎨

Pixel Palette ?? What was the color of the sunset yesterday? Or the color you would like to use in your vlog? Save the color of your moments with Pixe

Sue Cho 21 Aug 7, 2022
HEX color handling as an extension for UIColor. Written in Swift.

SwiftHEXColors HEX color handling as an extension for UIColor. Written in Swift.

Thi Doãn 692 Dec 22, 2022
HexColor is a simple extension that lets you initialize UIColors the way they were meant to be initialized: With hex integer values

HexColor is a simple extension that lets you initialize UIColors the way they were meant to be initialized: With hex integer values. Requirem

Tuomas Artman 103 Nov 24, 2022
A UIColor extension with CSS3 Color names.

CSS3ColorsSwift Overview CSS3ColorsSwift provides a UIColor extension with Web Color names. Demo Run the demo project in the Demo directory without ca

WorldDownTown 67 Aug 6, 2022
HEX color handling as an extension for UIColor

HEX color handling as an extension for UIColor. Written in Swift

Thi Doãn 692 Dec 22, 2022
ColorSlider is a SwiftUI view that displays a color slider

ColorSlider is a SwiftUI view that displays a color slider. It is used to dynamically select a color from a range of colors or grayscale.

workingDog 0 Apr 15, 2022
ColorWheel Test - An attempt at creating a Color Wheel to be utilized for color picking in SwiftUI utlizing various tutuorials on youtube

This code focuses on creating a Color Wheel in which a user will be able to select a desired color to then be implemented in another project that will display that color in an LED connected to an arduino

Gerardo Cerpa 0 Jan 15, 2022
ColorShift - A ViewModifier that will constantly update the color of a SwiftUI view

A ViewModifier that will constantly update the color of a SwiftUI view. The color will gradient slowly from one color to the next. By default, the initial color is randomly selected.

null 1 Feb 26, 2022
PrettyColors is a Swift library for styling and coloring text in the Terminal.

PrettyColors is a Swift library for styling and coloring text in the Terminal. The library outputs ANSI escape codes and conforms to ECMA Standard 48.

J.D. Healy 171 Aug 13, 2022
A pure Swift library for using ANSI codes. Basically makes command-line coloring and styling very easy!

Colors A pure Swift library for using ANSI codes. Basically makes command-line coloring and styling very easy! Note: Colors master requires Xcode 7.3

Chad Scira 27 Jun 3, 2021
UIGradient - A simple and powerful library for using gradient layer, image, color

UIGradient is now available on CocoaPods. Simply add the following to your project Podfile, and you'll be good to go.

Đinh Quang Hiếu 247 Dec 1, 2022
Colour blindness simulation and testing for iOS

Color Deficiency Snapshot Tests This package makes it easier for you to understand the implications of your app's design on users with various types o

James Sherlock 69 Sep 29, 2022
A powerful and easy to use live mesh gradient renderer for iOS.

MeshKit A powerful and easy to use live mesh gradient renderer for iOS. This project wouldn't be possible without the awesome work from Moving Parts a

Ethan Lipnik 51 Jan 1, 2023
ChromaColorPicker - An intuitive HSB color picker built in Swift

An intuitive HSB color picker built in Swift. Supports multiple selection handles and is customizable to your needs.

Jonathan Cardasis 536 Dec 29, 2022