UIColor轉換以及簡單擴充
概述
UIColor
也是我們開發中必然會用到的内容,這裡簡單的歸類了一些常用功能:
-
轉到hexString
UIColor
- 從
擷取PatternImage
UIColor
-
轉換成圖檔UIColor
這裡建立了分類
UIColor+MMAddition.{h,m}
來簡單的總結上述幾個點
檔案代碼UIColor+MMAddition.{h,m}下載下傳直接使用
下面也是全部代碼的介紹,可以Ctrl+C使用
API
1、+ (UIColor )colorWithHexString:(NSString )hexString
通過16進制hexString色值直接擷取
UIColor
對象
+ (UIColor *)colorWithHexString:(NSString *)hexString {
return [self colorWithHexString:hexString alpha:f];
}
+ (UIColor *)colorWithHexString:(NSString *)hexString alpha:(CGFloat)alpha {
NSString *cString = [[hexString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
if ([cString length] < )
return nil;
if ([cString hasPrefix:@"#"])
cString = [cString substringFromIndex:];
if ([cString length] != )
return nil;
NSString *rString = [cString substringWithRange:NSMakeRange(, )];
NSString *gString = [cString substringWithRange:NSMakeRange(, )];
NSString *bString = [cString substringWithRange:NSMakeRange(, )];
unsigned int r, g, b;
[[NSScanner scannerWithString:rString] scanHexInt:&r];
[[NSScanner scannerWithString:gString] scanHexInt:&g];
[[NSScanner scannerWithString:bString] scanHexInt:&b];
UIColor *hexColor = [UIColor colorWithRed:((float) r / f)
green:((float) g / f)
blue:((float) b / f)
alpha:alpha];
return hexColor;
}
2、+ (UIColor )colorWithUIImage:(UIImage )image
從一張純色圖擷取顔色
+ (UIColor *)colorWithUIImage:(UIImage *)image {
return [self colorWithPatternImage:image];
}
3、+ (UIImage )imageWithColor:(UIColor )color
由
UIColor
顔色擷取
UIImage
對象
+ (UIImage *)imageWithColor:(UIColor *)color {
CGRect rect = CGRectMake(f, f, f, f);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return theImage;
}
4、+ (UIImage )imageWithHexString:(NSString )hexString
由16進制
HexString
顔色擷取
UIImage
對象
+ (UIImage *)imageWithHexString:(NSString *)hexString {
return [self imageWithColor:[self colorWithHexString:hexString]];
}
PS:以上部分代碼需要配套使用