HexColor

2019-04-03  本文已影响0人  winsonGali

UIColor+Extend.h

#import <UIKit/UIKit.h>

@interface UIColor (Extend)

+ (instancetype)hexColor:(NSString *)hexColor alpha:(CGFloat)alpha;

@end

UIColor+Extend.m

#import "UIColor+Extend.h"

@implementation UIColor (Extend)

+ (instancetype)hexColor:(NSString *)hexColor alpha:(CGFloat)alpha {
    //检查alpha的值的正确性
    CGFloat alphalValue = 1;
    if (alpha >= 0 && alpha < 1) {
        alphalValue = alpha;
    }
    
    NSString *validHexChars = @"abcdefABCDEF0123456789";
    NSMutableString *filterHex = [[NSMutableString alloc] initWithCapacity:6];
    
    //过滤输入的颜色的十六进制字符串
    for (int i = 0; i < hexColor.length; i++) {
        unichar charFromInput = [hexColor characterAtIndex:i];
        NSString *hexChar = [NSString stringWithFormat:@"%c", charFromInput];
        if ([validHexChars rangeOfString:hexChar options:NSCaseInsensitiveSearch].location != NSNotFound) {
            [filterHex appendString:hexChar];
        }
    }
    
    //匹配字符串并转成RGB颜色
    if (filterHex.length == 6) {
        unsigned long long colorValue = 0;
        NSScanner *scanner = [[NSScanner alloc] initWithString:filterHex];
        [scanner scanHexLongLong:&colorValue];
        CGFloat red = ((colorValue & 0xFF0000) >> 16) / 255.0;
        CGFloat green = ((colorValue & 0x00FF00) >> 8) / 255.0;
        CGFloat blue = (colorValue & 0x0000FF) / 255.0;
        return [self colorWithRed:red green:green blue:blue alpha:alphalValue];
    }
    
    return [self colorWithRed:0 green:0 blue:0 alpha:alphalValue];
}

Usage:

self.view.bacgroundColor = [UIColor hexColor:@"FF6600", alpha:0.8];
上一篇下一篇

猜你喜欢

热点阅读