首页 > 代码库 > Objective C - UIColor
Objective C - UIColor
UIColor+Hex.h
UIColor+Hex.m#import <UIKit/UIKit.h> @interface UIColor (Hex) + (UIColor *) colorWithHexString: (NSString *) hexString; + (CGFloat) colorComponentFrom: (NSString *) string start: (NSUInteger) start length: (NSUInteger) length; @end
#import "UIColor+Hex.h" @interface UIColor() + (CGFloat) colorComponentFrom: (NSString *) string start: (NSUInteger) start length: (NSUInteger) length; @end @implementation UIColor(HexString) + (UIColor *) colorWithHexString: (NSString *) hexString { NSString *colorString = [[hexString stringByReplacingOccurrencesOfString: @"#" withString: @""] uppercaseString]; CGFloat alpha, red, blue, green; switch ([colorString length]) { case 3: // #RGB alpha = 1.0f; red = [self colorComponentFrom: colorString start: 0 length: 1]; green = [self colorComponentFrom: colorString start: 1 length: 1]; blue = [self colorComponentFrom: colorString start: 2 length: 1]; break; case 4: // #ARGB alpha = [self colorComponentFrom: colorString start: 0 length: 1]; red = [self colorComponentFrom: colorString start: 1 length: 1]; green = [self colorComponentFrom: colorString start: 2 length: 1]; blue = [self colorComponentFrom: colorString start: 3 length: 1]; break; case 6: // #RRGGBB alpha = 1.0f; red = [self colorComponentFrom: colorString start: 0 length: 2]; green = [self colorComponentFrom: colorString start: 2 length: 2]; blue = [self colorComponentFrom: colorString start: 4 length: 2]; break; case 8: // #AARRGGBB alpha = [self colorComponentFrom: colorString start: 0 length: 2]; red = [self colorComponentFrom: colorString start: 2 length: 2]; green = [self colorComponentFrom: colorString start: 4 length: 2]; blue = [self colorComponentFrom: colorString start: 6 length: 2]; break; default: [NSException raise:@"Invalid color value" format: @"Color value %@ is invalid. It should be a hex value of the form #RBG, #ARGB, #RRGGBB, or #AARRGGBB", hexString]; break; } return [UIColor colorWithRed: red green: green blue: blue alpha: alpha]; } + (CGFloat) colorComponentFrom: (NSString *) string start: (NSUInteger) start length: (NSUInteger) length { NSString *substring = [string substringWithRange: NSMakeRange(start, length)]; NSString *fullHex = length == 2 ? substring : [NSString stringWithFormat: @"%@%@", substring, substring]; unsigned hexComponent; [[NSScanner scannerWithString: fullHex] scanHexInt: &hexComponent]; return hexComponent / 255.0; } @end
Objective C - UIColor
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。