• Stars
    star
    256
  • Rank 159,219 (Top 4 %)
  • Language
    Objective-C
  • License
    Other
  • Created almost 13 years ago
  • Updated about 7 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

[DEPRECATED]

WARNING: THIS PROJECT IS DEPRECATED

It will not receive any future updates or bug fixes. If you are using it, please migrate to another solution.


Purpose

ColorUtils is a category on UIColor that extends it with some commonly needed features that were left out of the standard API.

UIColor is a thin wrapper around CGColor, which supports a wide variety of different formats, making it very flexible. This flexibility comes at a cost to usability for common tasks however; for example, it's non-trivial to access the red, green and blue components of an RGB color, and it is difficult to compare colors because [UIColor blackColor] is treated as different from [UIColor colorWithRed:0 green:0 blue:0 alpha:1] even though they are identical on screen. ColorUtils makes these tasks easy.

Another common problem is that RGBA UIColors are specified using four floating point values in the range 0.0 to 1.0, but virtually all graphics software treats colors as having integer components in the range 0 - 255, often represented as a hexadecimal string. ColorUtils lets you specify colors as hexadecimals so you can copy and paste values directly from PhotoShop.

Supported iOS & SDK Versions

  • Supported build target - iOS 8.0 (Xcode 6.0, Apple LLVM compiler 6.0)
  • Earliest supported deployment target - iOS 6.0
  • Earliest compatible deployment target - iOS 4.3

NOTE: 'Supported' means that the library has been tested with this version. 'Compatible' means that the library should work on this iOS version (i.e. it doesn't rely on any unavailable SDK features) but is no longer being tested for compatibility and may require tweaking or bug fixes to run correctly.

ARC Compatibility

As of version 1.1, ColorUtils requires ARC. If you wish to use ColorUtils in a non-ARC project, just add the -fobjc-arc compiler flag to the ColorUtils.m class. To do this, go to the Build Phases tab in your target settings, open the Compile Sources group, double-click iRate.m in the list and type -fobjc-arc into the popover.

If you wish to convert your whole project to ARC, comment out the #error line in ColorUtils.m, then run the Edit > Refactor > Convert to Objective-C ARC... tool in Xcode and make sure all files that you wish to use ARC for (including ColorUtils.m) are checked.

Installation

To use ColorUtils in an app, just drag the ColorUtils.h and .m files into your project.

Thread Safety

ColorUtils methods should be fully thread-safe, however note that calls to registerColor:forName: and colorWithString:/initWithString: will be queued and may cause deadlock if called concurrently from multiple threads.

Properties

@property (nonatomic, readonly) CGFloat red; @property (nonatomic, readonly) CGFloat green; @property (nonatomic, readonly) CGFloat blue; @property (nonatomic, readonly) CGFloat alpha;

These properties give you direct (read only) access to the red, green, blue and alpha color components. Now of course, not all UIColors have these attributes, so for monochromatic colors the red, green and blue values will all be the same value, and for non-RGB colors such as CMYK, patterned or indexed colors, these values will log a warning when accessed and return zero. To avoid generating these warnings, call the isMonochromeOrRGB method before attempting to access the components.

Methods

  • (void)registerColor:(UIColor *)color forName:(NSString *)name;

Register a custom color with a name for use with the colorWithString: method.

  • (UIColor *)colorWithString:(NSString *)string;
  • (UIColor *)initWithString:(NSString *)string;

These methods create a color object by parsing the supplied string. The string is first checked to see if it matches any standard color constants names (the check is case insensitive) and if not, an attempt is made to parse the string as a hexadecimal value.

Hexadecimal strings can be prefixed with #, 0x or nothing and can have 3, 6 or 8 digits. 6 digits is the standard rrggbb format, 8 is the same but with an alpha component, 3 is a shorthand used commonly in CSS, where each hex digit is repeated, so #29f becomes #2299ff, for example.

  • (UIColor *)colorWithRGBValue:(uint32_t)rgb;
  • (UIColor *)initWithRGBValue:(uint32_t)rgb;

These methods create a color using a single RGB value encoded as an integer. This may seem rather obscure until you realise that such a value can be created easily using a hexadecimal constant, e.g 0xff0000 for red. This is more efficient than using a hex string.

  • (UIColor *)colorWithRGBAValue:(uint32_t)rgba;
  • (UIColor *)initWithRGBAValue:(uint32_t)rgba;

This method is the same as colorWithRGBValue except that the input value includes an alpha component, e.g 0xff00007f for 50% transparent red. Do not mix up the colorWithRGBValue and colorWithRGBAValue methods as RGB integer values and RGBA integer values are not interchangeable.

  • (uint32_t)RGBValue;

This returns the color's RGB components as single integer value. This is useful for saving color values to disk, and can be used as the input to the colorWithRGBValue method to re-create the UIColor later. This value can be hard to interpret, but you can convert it to a more readable hex value using NSLog(@"color: %.6x", intColorValue). Note that this method only works for monochrome or RGB(A) colors. Any other format (e.g. pattern) will log a warning and return 0 (black).

  • (uint32_t)RGBAValue;

This method is the same as RGBValue except that the returned value includes an alpha component. You can convert this to a hex string using NSLog(@"color: %.8x", intColorValue). As above, this only works with monochrome or RGB(A) colors.

  • (NSString *)stringValue;

This method converts the color to a string by first matching it against known color constants, and returning their name if there's a match, and then by converting it to a 6 or 8 digit hex string, depending on whether the color has an alpha component. This value is useful if you want to log or display the color, and can also be used to save and re-create the color by passing the string to the colorWithString method.

  • (BOOL)isMonochromeOrRGB;

This method returns YES if the color is a monochrome or RGB-formatted color. Many of the ColorUtils methods only work correctly on these color types, so this can be useful to check.

  • (BOOL)isEquivalent:(id)object;

The standard UIColor isEqual method returns NO if two colors have the same appearance but a different number of components. This means that [UIColor blackColor] is treated as different from [UIColor colorWithRed:0 green:0 blue:0 alpha:1] even though they are identical on screen. The isEquivalent method compares the RGBAValue values of the colors instead, and so is a more convenient way to compare colors for equality. If the colors are not monochrom or RGB, this returns the result of isEqual: instead.

  • (BOOL)isEquivalentToColor:(UIColor *)color;

Same as isEquivalent, but slightly more efficient if you already know that the object being compared is a UIColor.

  • (UIColor *)colorWithBrightness:(CGFloat)brightness;

Applies a multiplier to the red, green and blue components of the color to vary the brightness. The brightness argument should be in the range 0.0 - x, with 0.0 returning black and 1.0 returning the original color and values gretaer than 1.0 making the color brighter. Alpha is unaffected.

  • (UIColor *)colorBlendedWithColor:(UIColor *)color factor:(CGFloat)factor;

This method blends between two colors, using the supplied factor to control the level of blending. The factor value should be in the range 0.0 - 1.0, with 0.0 returning the receiver and 1.0 returning the supplied color.

Color Constant Names

The list of standard color constants can be found in the UIColor documentation, but is repeated here for convenience. Using color constants where possible reduces memory and improves performance by avoiding creating multiple identical UIColor objects in memory.

black -  Equivalent to 0.0 white
darkgray -  Equivalent to 0.333 white
lightgray -  Equivalent to 0.667 white
white -  Equivalent to 1.0 white
gray -  Equivalent to 0.5 white
red -  Equivalent to 1.0, 0.0, 0.0 RGB
green -  Equivalent to 0.0, 1.0, 0.0 RGB
blue -  Equivalent to 0.0, 0.0, 1.0 RGB
cyan -  Equivalent to 0.0, 1.0, 1.0 RGB
yellow -  Equivalent to 1.0, 1.0, 0.0 RGB
magenta -  Equivalent to 1.0, 0.0, 1.0 RGB
orange -  Equivalent to 1.0, 0.5, 0.0 RGB
purple -  Equivalent to 0.5, 0.0, 0.5 RGB
brown -  Equivalent to 0.6, 0.4, 0.2 RGB
clear -  Equivalent to 0.0 white, 0.0 alpha

You can register custom named colors using the registerColor:forName: method. Once registered, your custom color will be read/written by the colorWithString/stringValue methods, just like the standard colors.

Example

Most of the methods and properties are fairly self-explanatory, but there is an example included that shows how to set colors by name or with hexadecimal strings.

Release notes

Version 1.1.3

  • Added missing UIKit import statement
  • ColorUtils is now fully thread-safe

Version 1.1.2

  • Removed upper limit on colorWithBrightness: method.

Version 1.1.1

  • Fixed some type mismatch warnings affecting arm64 builds

Version 1.1

  • Now requires ARC
  • Added registerColor:forName: method for adding bespoke named colors
  • Added colorWithBrightness: and colorBlendedWithColor: methods
  • Now complies with -Wextra warning level
  • Added CocoaPods podspec file

Version 1.0.3

  • Moved ARCHelper macros out of .h file
  • Renamed class files for future flexibility
  • Updated example for iOS6 and ARC

Version 1.0.2

  • Added automatic support for ARC compile targets
  • Now requires Apple LLVM 3.0 compiler target

Version 1.0.1

  • Fixed potential crash due to an incorrect retain count when initialising colors using a name string, e.g. 'blue'.

Version 1.0

  • Initial release

More Repositories

1

iCarousel

A simple, highly customisable, data-driven 3D carousel for iOS and Mac OS
Objective-C
11,999
star
2

SwiftFormat

A command-line tool and Xcode Extension for formatting Swift code
Swift
7,781
star
3

FXBlurView

[DEPRECATED]
Objective-C
4,942
star
4

iRate

[DEPRECATED]
Objective-C
4,100
star
5

FXForms

[DEPRECATED]
Objective-C
2,926
star
6

SwipeView

SwipeView is a class designed to simplify the implementation of horizontal, paged scrolling views on iOS. It is based on a UIScrollView, but adds convenient functionality such as a UITableView-style dataSource/delegate interface for loading views dynamically, and efficient view loading, unloading and recycling.
Objective-C
2,646
star
7

layout

A declarative UI framework for iOS
Swift
2,231
star
8

iVersion

[DEPRECATED]
Objective-C
1,947
star
9

NullSafe

NullSafe is a simple category on NSNull that returns nil for unrecognised messages instead of throwing an exception
Objective-C
1,943
star
10

RetroRampage

Tutorial series demonstrating how to build a retro first-person shooter from scratch in Swift
Swift
1,486
star
11

XMLDictionary

[DEPRECATED]
Objective-C
1,139
star
12

AutoCoding

AutoCoding is a category on NSObject that provides automatic support for NSCoding and NSCopying to every object.
Objective-C
1,068
star
13

GZIP

A simple NSData category for gzipping/unzipping data in iOS and Mac OS
Objective-C
983
star
14

FastCoding

A faster and more flexible binary file format replacement for NSCoding, Property Lists and JSON
C
976
star
15

AsyncImageView

[DEPRECATED]
Objective-C
906
star
16

iConsole

[DEPRECATED]
Objective-C
859
star
17

Expression

A cross-platform Swift library for evaluating mathematical expressions at runtime
Swift
822
star
18

FXLabel

[DEPRECATED]
Objective-C
816
star
19

CountryPicker

CountryPicker is a custom UIPickerView subclass that provides an iOS control allowing a user to select a country from a list. It can optionally display a flag next to each country name, and the library includes a set of 249 high-quality, public domain flag images from FAMFAMFAM (http://www.famfamfam.com/lab/icons/flags/) that have been painstakingly re-named by country code to work with the library.
Objective-C
740
star
20

Euclid

A Swift library for creating and manipulating 3D geometry
Swift
637
star
21

SoundManager

Simple sound and music player class for playing audio on Mac and iPhone
Objective-C
630
star
22

FXImageView

FXImageView is a class designed to simplify the application of common visual effects such as reflections and drop-shadows to images, and also to help the performance of image loading by handling it on a background thread.
Objective-C
628
star
23

Base64

[DEPRECATED]
Objective-C
578
star
24

FXKeychain

[DEPRECATED]
Objective-C
554
star
25

MustOverride

Provides a macro that you can use to ensure that a method of an abstract base class *must* be overriden by its subclasses.
Objective-C
523
star
26

LayerSprites

LayerSprites is a library designed to simplify the use of sprite sheets (image maps containing multiple sub-images) in UIKit applications without using OpenGL or 3rd-party game libraries. Can load sprite sheets in the Coco2D format.
Objective-C
504
star
27

GLView

[DEPRECATED]
Objective-C
477
star
28

FXNotifications

An alternative API for NSNotificationCenter that doesn't suck
Objective-C
392
star
29

ShapeScript

The ShapeScript 3D modeling app for macOS and iOS
Swift
391
star
30

LRUCache

LRUCache is an open-source replacement for NSCache that behaves in a predictable, debuggable way
Swift
378
star
31

VectorMath

A Swift library for Mac and iOS that implements common 2D and 3D vector and matrix functions, useful for games or vector-based graphics
Swift
367
star
32

ReflectionView

[DEPRECATED]
Objective-C
359
star
33

Swiftenstein

Simple Wolfenstein 3D clone written in Swift
Swift
359
star
34

JPNG

JPNG is a bespoke image file format that combines the compression benefits of JPEG with the alpha channel support of a PNG file. The JPNG library provides an Objective-C implementation of this format along with transparent JPNG loading support for iOS and Mac OS.
Objective-C
340
star
35

StandardPaths

StandardPaths is a category on NSFileManager for simplifying access to standard application directories on iOS and Mac OS and abstracting the iCloud backup flags on iOS. It also provides support for working with device-specific file suffixes, such as the @2x suffix for Retina displays, or the -568h suffix for iPhone 5 and can optionally swizzle certain UIKit methods to support these suffixes more consistently.
Objective-C
336
star
36

ViewUtils

ViewUtils is a collection of category methods designed that extend UIView with all the handy little properties and functionality that you always wished were built-in to begin with.
Objective-C
324
star
37

FXPageControl

Simple, drop-in replacement for the iPhone UIPageControl that allows customisation of the dot colour, size and spacing.
Objective-C
298
star
38

BaseModel

BaseModel provides a base class for building model objects for your iOS or Mac OS projects. It saves you the hassle of writing boilerplate code, and encourages good practices by reducing the incentive to cut corners in your model implementation.
Objective-C
288
star
39

OrderedDictionary

This library provides OrderedDictionary and MutableOrderedDictionary subclasses.
Objective-C
278
star
40

Tribute

A command-line tool for tracking Swift project licenses
Swift
246
star
41

OSNavigationController

[DEPRECATED]
Objective-C
233
star
42

Consumer

Mac and iOS library for parsing structured text
Swift
226
star
43

iNotify

[DEPRECATED]
Objective-C
225
star
44

FPSControls

An experimental implementation of touch-friendly first-person shooter controls using SceneKit and Swift
Swift
215
star
45

OSCache

OSCache is an open-source re-implementation of NSCache that behaves in a predictable, debuggable way.
Objective-C
200
star
46

Chess

A simple Chess game for iOS, written in Swift
Swift
177
star
47

RequestQueue

[DEPRECATED]
Objective-C
174
star
48

FXReachability

Lightweight reachability class for Mac and iOS
Objective-C
173
star
49

Sprinter

A library for formatting strings on iOS and macOS
Swift
166
star
50

CryptoCoding

CryptoCoding is a superset of the NSCoding protocol that allows for simple, seamless AES encryption of any NSCoding-compatible object.
Objective-C
148
star
51

RequestUtils

A collection of category methods designed to simplify the process of HTTP request construction and manipulation in Cocoa.
Objective-C
142
star
52

CubeController

CubeController is a UIViewController subclass that can be used to create a rotating 3D cube navigation.
Objective-C
142
star
53

HTMLLabel

[DEPRECATED]
Objective-C
139
star
54

NSOperationStack

[DEPRECATED]
Objective-C
118
star
55

SVGPath

Cross-platform Swift library for parsing SVGPath strings
Swift
111
star
56

HRCoder

HRCoder is a replacement for the NSKeyedArchiver and NSKeyedUnarchiver classes that uses a human-readable/editable format that can easily be stored in a regular Plist or JSON file.
Objective-C
104
star
57

iPrompt

[DEPRECATED]
Objective-C
99
star
58

Presentations

Code samples and projects for presentations that I have given
Objective-C
98
star
59

FXPhotoEditView

[DEPRECATED]
Objective-C
92
star
60

StackView

StackView is a class designed to simplify the implementation of vertical stacks of views on iOS. You can think of it as a bit like a simplified version of UITableView.
Objective-C
73
star
61

WebContentView

[DEPRECATED]
Objective-C
69
star
62

StringCoding

StringCoding is a simple Mac/iOS library for setting object properties of any type using string values. It can automatically detect the property type and attempt to interpret the string as the right kind of value. It's particularly oriented towards iOS app theming (see README for details).
Objective-C
57
star
63

ArrayUtils

[DEPRECATED]
Objective-C
49
star
64

Swune

Swift/UIKit reimplementation of the Dune II RTS game
Swift
46
star
65

Parsing

Supporting code for my talk entitled "Parsing Formal Languages with Swift"
Swift
42
star
66

MACAddress

[DEPRECATED]
Objective-C
39
star
67

FXParser

[DEPRECATED]
Objective-C
34
star
68

RotateView

Objective-C
34
star
69

RandomSequence

A class for creating independent, repeatable pseudorandom number sequences on Mac and iOS
Objective-C
28
star
70

FloatyBalloon

This is the source code for a simple game called Floaty Balloon, based on the gameplay of Flappy Bird. It was created as a tutorial for http://iosdevelopertips.com
Objective-C
25
star
71

Concurrency

Full source code for a simple currency calculator app
Objective-C
15
star
72

FXJSON

[DEPRECATED]
Objective-C
15
star
73

PNGvsJPEG

This is a simple benchmark app to compare JPEG vs PNG loading performance on iOS. Spoiler: JPEG wins.
Objective-C
6
star