美文网首页
iOS 颜色转换 (10进制<—>16进制)

iOS 颜色转换 (10进制<—>16进制)

作者: 吃货_X | 来源:发表于2019-05-16 16:52 被阅读0次
    /** 根据颜色获取RGB值 */
    - (NSArray *)getRGBWithColor:(UIColor *)color{
        CGFloat red = 0.0;
        CGFloat green = 0.0;
        CGFloat blue = 0.0;
        CGFloat alpha = 0.0;
        [color getRed:&red green:&green blue:&blue alpha:&alpha];
        return @[@(red), @(green), @(blue)];
    }
    /** RGB转十六进制 */
    - (NSArray *)getColorWithRgb:(NSArray *)array{
        int red,green,blue;
        [[NSScanner scannerWithString:[NSString stringWithFormat:@"%@",array[0]]] scanInt:&red];
        [[NSScanner scannerWithString:[NSString stringWithFormat:@"%@",array[1]]] scanInt:&green];
        [[NSScanner scannerWithString:[NSString stringWithFormat:@"%@",array[2]]] scanInt:&blue];
        NSMutableArray *rgbArray = @[@(red),@(green),@(blue)].mutableCopy;
        for (int i = 0; i < rgbArray.count; i++) {
            NSString *value = [NSString stringWithFormat:@"%02x",[rgbArray[i] intValue]];
            rgbArray[i] = value;
        }
        return @[[rgbArray componentsJoinedByString:@""],GetColor(red, green, blue, 1)];
    }
    /** 16进制转RGB */
    - (NSArray *)getColor:(NSString *)hexColor {
        unsigned int red,green,blue;
        NSRange range;
        range.length = 2;
        range.location = 0;
        [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&red];
        range.location = 2;
        [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&green];
        range.location = 4;
        [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&blue];
        return @[@[@(red),@(green),@(blue)],GetColor(red, green, blue, 1)];
        
    }
    
    备注:以上代码部分来自网上文档
    
    

    相关文章

      网友评论

          本文标题:iOS 颜色转换 (10进制<—>16进制)

          本文链接:https://www.haomeiwen.com/subject/slaiaqtx.html