十六进制颜色 转为 uicolor ,定义有颜色的字符串,不同颜色字符串的拼接



/**
 *  拼接字符串
 */
-(NSMutableAttributedString *)obtainResultWithColorAndStringDictionary:(NSDictionary *)dic
{
    NSMutableAttributedString * result = [[NSMutableAttributedString alloc] init];
    NSArray * keys = [dic allKeys];
    for (int i = 0; i < keys.count; i++) {
        NSString * color = [dic objectForKey:[keys objectAtIndex:i]];
        NSString * content = [keys objectAtIndex:i];
        [result appendAttributedString:[self getNewAttributedStringWith:color And:content]];
    }
    return result;
}

/**
 *  创建有颜色的字符串
 */
-(NSAttributedString *)getNewAttributedStringWith:(NSString *)hexColor And:(NSString *)contents
{
    UIColor * color = [self colorWithHexString:hexColor];
    NSAttributedString * attrString = [[NSAttributedString alloc] initWithString:contents attributes:@{NSForegroundColorAttributeName:color}];
    
    return attrString;
}

/**
 *  十六进制 转颜色
 */
-(UIColor *)colorWithHexString:(NSString *)color
{
    //去掉后面的空格和换行
    NSString * colorString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    if (colorString.length < 6) {
        return [UIColor clearColor];
    }
    
    //去除前缀
    if ([colorString hasPrefix:@"0X"]) {
        colorString = [colorString substringFromIndex:2];
    }else if ([colorString hasPrefix:@"#"]) {
        colorString = [colorString substringFromIndex:1];
    }else if (colorString.length != 6) {
        return [UIColor clearColor];
    }
    
    //分割字符串,取出red  green   blue
    NSRange range;
    range.location = 0;
    range.length = 2;
    
    NSString * redString = [colorString substringWithRange:range];
    range.location = 2;
    NSString * greenString = [colorString substringWithRange:range];
    range.location = 4;
    NSString * blueString = [colorString substringWithRange:range];
    
    //scan values
    unsigned int red,green,blue;
    [[NSScanner scannerWithString:redString] scanHexInt:&red];
    [[NSScanner scannerWithString:greenString] scanHexInt:&green];
    [[NSScanner scannerWithString:blueString] scanHexInt:&blue];
    
    return [UIColor colorWithRed:((float)red / 255.0) green:((float)green / 255.0) blue:((float)blue / 255.0) alpha:1.0];
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值