美文网首页
字符串"#333333"转UIColor对象

字符串"#333333"转UIColor对象

作者: _菩提本无树_ | 来源:发表于2025-02-20 16:01 被阅读0次
+ (UIColor *)colorWithHexString:(NSString *)hexString {
    // 去掉字符串中的‘#’前缀(如果有)
    if ([hexString hasPrefix:@"#"]) {
        hexString = [hexString substringFromIndex:1];
    }

    // 颜色字符串长度应为6或8(6: RGB,8: ARGB)
    NSUInteger length = [hexString length];
    if (length != 6 && length != 8) {
        return nil;
    }

    unsigned int rgbValue = 0;
    NSScanner *scanner = [NSScanner scannerWithString:hexString];
    [scanner scanHexInt:&rgbValue];

    CGFloat red, green, blue, alpha;

    if (length == 6) {
        red = ((rgbValue & 0xFF0000) >> 16) / 255.0;
        green = ((rgbValue & 0x00FF00) >> 8) / 255.0;
        blue = (rgbValue & 0x0000FF) / 255.0;
        alpha = 1.0;
    } else {
        alpha = ((rgbValue & 0xFF000000) >> 24) / 255.0;
        red = ((rgbValue & 0x00FF0000) >> 16) / 255.0;
        green = ((rgbValue & 0x0000FF00) >> 8) / 255.0;
        blue = (rgbValue & 0x000000FF) / 255.0;
    }

    return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}

相关文章

网友评论

      本文标题:字符串"#333333"转UIColor对象

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