将颜色转为图片
- (UIImage *)imageWithColor:(UIColor *)color {
CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
16进制色值使用:
* 宏定义使用
/** 颜色宏定义 */
#define UIColorFromHex(hexValue) [UIColor colorWithRed:((float)((hexValue & 0xFF0000) >> 16))/255.0 green:((float)((hexValue & 0xFF00) >> 8))/255.0 blue:((float)(hexValue & 0xFF))/255.0 alpha:1.0]
* 方法使用
#pragma mark - hex string convert to color object
+ (UIColor *) colorWithHexString:(NSString *)hexString{
NSString *cString = [[hexString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
//hexString should six-eight character
if ([cString length] < 6) {
return [UIColor clearColor];
}
//if hexString has @"0X" prefix
if ([cString hasPrefix:@"0X"])
cString = [cString substringFromIndex:2];
//if hexString has @"#"" prefix
if ([cString hasPrefix:@"#"])
cString = [cString substringFromIndex:1];
// 如果hexString 有@"..FF"后缀...必须是在cString.length长度大于6的情况下
if (cString.length > 6) {
if ([cString hasSuffix:@"FF"]) {
cString = [cString substringToIndex:cString.length-2];
}
}
if ([cString length] != 6)
return [UIColor clearColor];
//RGB exchange
NSRange range;
range.location = 0;
range.length = 2;
//R
NSString *rString = [cString substringWithRange:range];
//G
range.location = 2;
NSString *gString = [cString substringWithRange:range];
//B
range.location = 4;
NSString *bString = [cString substringWithRange:range];
// unsigned int object
unsigned int r, g, b;
[[NSScanner scannerWithString:rString] scanHexInt:&r];
[[NSScanner scannerWithString:gString] scanHexInt:&g];
[[NSScanner scannerWithString:bString] scanHexInt:&b];
return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}
渐变色生成
#pragma mark - gradient color--渐变色生成
/**
return `CAGradienLayer*`
[sysView.layer addSublayer:##CAGradientLayer##]; //添加layer
*/
+ (CAGradientLayer *)setGradualChangingColor:(CGRect)gradientLayerFrame fromColor:(NSString *)fromHexColorStr toColor:(NSString *)toHexColorStr {
// CAGradientLayer类对其绘制渐变背景颜色、填充层的形状(包括圆角)
CAGradientLayer *gradientLayer = [CAGradientLayer layer];
gradientLayer.frame = gradientLayerFrame;
// 创建渐变色数组,需要转换为CGColor颜色
gradientLayer.colors = @[(__bridge id)[self colorWithHexString:fromHexColorStr].CGColor,(__bridge id)[self colorWithHexString:toHexColorStr].CGColor];
// 设置渐变颜色方向,左上点为(0,0), 右下点为(1,1)
gradientLayer.startPoint = CGPointMake(0, 0);
gradientLayer.endPoint = CGPointMake(1, 1);
// 设置颜色变化点,取值范围 0.0~1.0
gradientLayer.locations = @[@0,@1];
return gradientLayer;
}
网友评论