Created
November 20, 2012 00:15
-
-
Save Higgcz/4115080 to your computer and use it in GitHub Desktop.
I made a category on UIColor which allows to create color from hex code (eg.: #498ea8). I have tried to use different methods to get number from hex string, but all of them was to slow, something about 0.022 - 0.040 ms. This is the fastest way I've found
This file contains hidden or 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
// | |
// UIColor+HashParser.h | |
// | |
// Created by Vojtech Micka on 11/19/12. | |
// Copyright (c) 2012 All rights reserved. | |
// | |
#import <UIKit/UIKit.h> | |
@interface UIColor (HexParser) | |
+ (UIColor *) colorWithHex:(NSString *)hex andAlpha:(CGFloat)alpha; | |
@end |
This file contains hidden or 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
// | |
// UIColor+HashParser.m | |
// | |
// Created by Vojtech Micka on 11/19/12. | |
// Copyright (c) 2012 All rights reserved. | |
// | |
#import "UIColor+HexParser.h" | |
@implementation UIColor (HexParser) | |
+ (UIColor *) colorWithHex:(NSString *)hex andAlpha:(CGFloat)alpha { | |
if ( [hex hasPrefix:@"#"] ) hex = [hex substringFromIndex:1]; | |
size_t lengthOfChars = 6, colorMax = 255; | |
unsigned char * colors = (unsigned char *) malloc(sizeof(unsigned char) * 3); | |
unichar * chars = (unichar *) malloc(sizeof(unichar) * lengthOfChars); | |
unichar temp; | |
[hex getCharacters:chars range:(NSRange) {0, [hex length]}]; | |
for ( int i = 0; i < lengthOfChars; i += 2 ) { | |
temp = *(chars + i); | |
if ( temp >= '0' && temp <= '9' ) { | |
*(colors + i/2) = (unsigned char) (temp - '0') << 4; | |
} else if ( temp >= 'a' && temp <= 'f' ) { | |
*(colors + i/2) = (unsigned char) (temp - 'a' + 10) << 4; | |
} else if ( temp >= 'A' && temp <= 'F' ) { | |
*(colors + i/2) = (unsigned char) (temp - 'A' + 10) << 4; | |
} else { | |
*(colors + i/2) = 0; | |
} | |
temp = *(chars + i + 1); | |
if ( temp >= '0' && temp <= '9' ) { | |
*(colors + i/2) += (unsigned char) (temp - '0'); | |
} else if ( temp >= 'a' && temp <= 'f' ) { | |
*(colors + i/2) += (unsigned char) (temp - 'a' + 10); | |
} else if ( temp >= 'A' && temp <= 'F' ) { | |
*(colors + i/2) += (unsigned char) (temp - 'A' + 10); | |
} | |
} | |
return [UIColor colorWithRed:((CGFloat) *(colors + 0) / colorMax) | |
green:((CGFloat) *(colors + 1) / colorMax) | |
blue:((CGFloat) *(colors + 2) / colorMax) | |
alpha:alpha]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment