Last active
August 29, 2015 13:56
-
-
Save r3econ/9132167 to your computer and use it in GitHub Desktop.
UIColor Extensions.
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
@interface UIColor (Extensions) | |
/** | |
Returns a UIColor for a color given in a hexadecimal string format. | |
Such as #00FF00. | |
*/ | |
+ (UIColor *)colorWithHexString:(NSString *)hexString; | |
/** | |
Returns a NSString with a hexadecimal value (HTML/CSS style) of the color. | |
Example: "ff8af1". | |
*/ | |
- (NSString *)hexString; | |
/** | |
Returns a random UIColor. | |
*/ | |
+ (UIColor *)randomColor; | |
@end |
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 "UIColor+Extensions.h" | |
@implementation UIColor (Extensions) | |
/** | |
Returns a UIColor for a color given in a hexadecimal string format. | |
Such as #00FF00. | |
*/ | |
+ (UIColor *)colorWithHexString:(NSString *)hexString | |
{ | |
unsigned rgbValue = 0; | |
// Create scanner with given string. | |
NSScanner *scanner = [NSScanner scannerWithString:hexString]; | |
// Skip the "#" character (if any). | |
[scanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:@"#"]]; | |
// Get the hex value from string. | |
[scanner scanHexInt:&rgbValue]; | |
// Create and return a UIColor. | |
return [UIColor colorWithRed:((rgbValue & 0xFF0000) >> 16)/255.0 | |
green:((rgbValue & 0xFF00) >> 8)/255.0 | |
blue:(rgbValue & 0xFF)/255.0 | |
alpha:1.0]; | |
} | |
/** | |
Returns a NSString with a hexadecimal value (HTML/CSS style) of the color. | |
Example: "ff8af1". | |
*/ | |
- (NSString *)hexString | |
{ | |
const CGFloat *components = CGColorGetComponents(self.CGColor); | |
CGFloat r = components[0]; | |
CGFloat g = components[1]; | |
CGFloat b = components[2]; | |
return [NSString stringWithFormat:@"%02lX%02lX%02lX", | |
lroundf(r * 255), | |
lroundf(g * 255), | |
lroundf(b * 255)]; | |
} | |
/** | |
Returns a random UIColor. | |
*/ | |
+ (UIColor *)randomColor | |
{ | |
// 0.0 to 1.0 | |
CGFloat hue = ( arc4random() % 256 / 256.0 ); | |
// 0.5 to 1.0, away from white | |
CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5; | |
// 0.5 to 1.0, away from black. | |
CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5; | |
return [UIColor colorWithHue:hue | |
saturation:saturation | |
brightness:brightness | |
alpha:1]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment