Instantly share code, notes, and snippets.

Embed
What would you like to do?
Hex から UIColor の作成
#import <Foundation/Foundation.h>
@interface UIColor (Hex)
- (UIColor *) initWithHex:(NSString *)hexString alpha:(CGFloat)alpha;
@end
@implementation UIColor (Hex)
- (UIColor *) initWithHex:(NSString *)string alpha:(CGFloat)alpha {
UIColor *color = nil;
if (string && [string length] == 7) {
NSString *colorString = [NSString stringWithFormat:
@"0x%@ 0x%@ 0x%@",
[string substringWithRange:NSMakeRange(1, 2)],
[string substringWithRange:NSMakeRange(3, 2)],
[string substringWithRange:NSMakeRange(5, 2)]];
unsigned red, green, blue;
NSScanner *scanner = [NSScanner scannerWithString:colorString];
if ([scanner scanHexInt:&red] && [scanner scanHexInt:&green] && [scanner scanHexInt:&blue]) {
color = [[UIColor alloc] initWithRed:(float)red / 0xff
green:(float)green / 0xff
blue:(float)blue / 0xff
alpha:alpha];
}
}
return color;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment