美文网首页
随机颜色

随机颜色

作者: nothing_c | 来源:发表于2016-10-29 00:58 被阅读5次

    //  UIColor+Hex.m创建继承于UIColor的类别 随机颜色


    UIColor+Hex.h

    + (UIColor *)colorWithHexString:(NSString *)hexSting;


    UIColor+Hex.m

    //  UIColorDemo

    #import"UIColor+Hex.h"

    #define RGBCOLOR(r,g,b) [UIColor colorWithRed:r/255.0green:g/255.0blue:b/255.0alpha:1]

    @implementation UIColor (Hex)

    + (UIColor *)colorWithHexString:(NSString *)hexSting {

    //修剪字符串去掉其中的特殊字符和空格

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

    //#55DDBB 55->R DD->G BB->B长度小于6不符合要求

    if([cStringlength] < 6) {

    return[UIColor clearColor];

    }

    //如果是0X开头,那么从第二个字符开始剪切字符串

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

    cString = [cString substringFromIndex:2];

    }

    //如果是以#开头,那么从第一个字符开始剪切字符串

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

    cString = [cString substringFromIndex:1];

    }

    //如果剪切到的字符串长度不是6也不符合要求

    if([cString length] != 6) {

    return[UIColor clearColor];

    }

    //0123456789ABCDEF字符集

    //超出字符集不可使用

    NSCharacterSet *hexSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789ABCDEF"];

    NSRange range;

    range.location= 0;

    range.length= 2;

    NSString *rString = [cString substringWithRange:range];

    NSCharacterSet *rSet = [NSCharacterSet characterSetWithCharactersInString:rString];

    range.location= 2;

    NSString *gString = [cString substringWithRange:range];

    NSCharacterSet *gSet = [NSCharacterSet characterSetWithCharactersInString:gString];

    range.location= 4;

    NSString *bString = [cString substringWithRange:range];

    NSCharacterSet *bSet = [NSCharacterSet characterSetWithCharactersInString:bString];

    if(![hexSetisSuper setOfSet:rSet] || ![hexSetisSuper setOfSet:gSet] || ![hexSetisSuper setOfSet:bSet]) {

    return[UIColor clearColor];

    }

    unsigned int r,g,b;

    [[NSScanner scannerWithString:rString] scanHexInt:&r];

    [[NSScanner scannerWithString:gString] scanHexInt:&g];

    [[NSScanner scannerWithString:bString] scanHexInt:&b];

    return RGBCOLOR(r, g, b);

    }

    相关文章

      网友评论

          本文标题:随机颜色

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