How can I convert RGB hex string into UIColor in objective-c?

后端 未结 4 1994
终归单人心
终归单人心 2020-11-30 10:17

I have color values coming from the url data is like this, \"#ff33cc\". How can I convert this value into UIColor? I am attempting with the following lines of code. I am not

4条回答
  •  醉梦人生
    2020-11-30 10:56

    I have made a function which works in the following cases:- 1) with or without # 2) both 3 and 6 character long values #000 as well as #000000 3) In case of extra digits more than six it ignores the extra digits

    //Function Call
    UIColor *organizationColor = [self colorWithHexString:@"#AAAAAAAAAAAAA" alpha:1];
    
    //Function
    - (UIColor *)colorWithHexString:(NSString *)str_HEX  alpha:(CGFloat)alpha_range{
        NSString *noHashString = [str_HEX stringByReplacingOccurrencesOfString:@"#" withString:@""]; // remove the #
    
        int red = 0;
        int green = 0;
        int blue = 0;
    
    if ([str_HEX length]<=3)
        {
            sscanf([noHashString UTF8String], "%01X%01X%01X", &red, &green, &blue);
            return  [UIColor colorWithRed:red/16.0 green:green/16.0 blue:blue/16.0 alpha:alpha_range];
        }
    else if ([str_HEX length]>7)
        {
            NSString *mySmallerString = [noHashString substringToIndex:6];
            sscanf([mySmallerString UTF8String], "%02X%02X%02X", &red, &green, &blue);
            return  [UIColor colorWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:alpha_range];
        }
    else
    {
        sscanf([noHashString UTF8String], "%02X%02X%02X", &red, &green, &blue);
        return  [UIColor colorWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:alpha_range];
    }}
    

提交回复
热议问题