您的位置:首页 > 产品设计 > UI/UE

16进制色值转换UIColor,UILabel自适应宽度

2016-07-27 00:00 309 查看
摘要: 简单封装,16进制色值转换成UIColor,直接使用,以及Label自适应宽度,提高开发。

如:#1e1e1e #ff5f5f转换成UIColor

- (UIColor *) colorWithHexString: (NSString *)color

{

NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];

// String should be 6 or 8 characters

if ([cString length] < 6) {

return [UIColor clearColor];

}

// strip 0X if it appears

if ([cString hasPrefix:@"0X"])

cString = [cString substringFromIndex:2];

if ([cString hasPrefix:@"#"])

cString = [cString substringFromIndex:1];

if ([cString length] != 6)

return [UIColor clearColor];

// Separate into r, g, b substrings

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];

// Scan values

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];

}

// 计算label的自适应宽度

- (CGFloat)getTextWidthForString:(NSString *)string with:(CGFloat)height with:(UIFont *)font{

CGRect rect = [string boundingRectWithSize:CGSizeMake(MAXFLOAT, height) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil];

return rect.size.width;

}

RGB 色值处理

定义成宏

#define RGBColorMake(_R_,_G_,_B_,_alpha_) [UIColor colorWithRed:_R_/255.0 green:_G_/255.0 blue:_B_/255.0 alpha:_alpha_]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息