iOS RGB颜色封装

使用类别创建

.h文件

#import <UIKit/UIKit.h>

@interface UIColor (HexColor)

+ (UIColor *)colorWithHex:(NSString *)hex;

@end

.m文件

#import "UIColor+HexColor.h"

@implementation UIColor (HexColor)

+ (UIColor *)colorWithHex:(NSString *)hex {
    unsigned int red, green, blue;
    NSRange range;
    range.length = 2;
    
    range.location = 0;
    if (hex.length == 7) {
        range.location = 1;
    }
    [[NSScanner scannerWithString:[hex substringWithRange:range]]scanHexInt:&red];
    range.location += 2;
    [[NSScanner scannerWithString:[hex substringWithRange:range]]scanHexInt:&green];
    range.location += 2;
    [[NSScanner scannerWithString:[hex substringWithRange:range]]scanHexInt:&blue];
    
    return [UIColor colorWithRed:(float)(red / 255.0) green:(float)(green / 255.0) blue:(float)(blue / 255.0) alpha:1.0];
}

@end

还有一个类似的方法,代码如下:

+ (UIColor *)colorWithHex:(NSString *)hex {  
        // Remove `#` and `0x`  
        if ([hex hasPrefix:@"#"]) {  
             hex = [hex substringFromIndex:1];  
        } else if ([hex hasPrefix:@"0x"]) {  
            hex = [hex substringFromIndex:2];  
        }  
      
        // Invalid if not 3, 6, or 8 characters  
        NSUInteger length = [hex length];  
        if (length != 3 && length != 6 && length != 8) {  
            return nil;  
        }  
      
        // Make the string 8 characters long for easier parsing  
        if (length == 3) {  
            NSString *r = [hex substringWithRange:NSMakeRange(01)];  
            NSString *g = [hex substringWithRange:NSMakeRange(11)];  
            NSString *b = [hex substringWithRange:NSMakeRange(21)];  
            hex = [NSString stringWithFormat:@"%@%@%@%@%@%@ff",                   r, r, g, g, b, b];  
        } else if (length == 6) {  
            hex = [hex stringByAppendingString:@"ff"];  
        }  
  
    CGFloat red = [[hex substringWithRange:NSMakeRange(02)] _hexValue] / 255.0f;  
        CGFloat green = [[hex substringWithRange:NSMakeRange(22)] _hexValue] / 255.0f;  
        CGFloat blue = [[hex substringWithRange:NSMakeRange(42)] _hexValue] / 255.0f;  
        CGFloat alpha = [[hex substringWithRange:NSMakeRange(62)] _hexValue] / 255.0f;  
          
    return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];  
    
}  
原文地址:https://www.cnblogs.com/DWdan/p/4818779.html