开发者

HEX to UIColorfromRGB

I'm following a tutorial here

It's fairly straight开发者_JAVA技巧 forward and simple, only 2 steps. But on the last step, I have the HEX code in a UITextField as hexText.text, but how do i put that into UIColorFromRGB?


here is a solution that avoids the macro stuff. You can add it to a category to UIColor and use it more nicely.


Sorin has the right idea here I think. Much more cocoa-like, and will result in fewer headaches. To answer your question at a high level, you'd need to convert your string to a hexadecimal number, and then pass that resulting value in to the macro. I think you'd be better served just passing the string value into the category listed in Sorin's link.


This will solve any case

+ (UIColor *) colorWithHexString: (NSString *) stringToConvert{
    NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    unsigned int r, g, b,alpha = 1;
    NSRange range;
    range.location = 0;
    range.length = 2;

    // String should be 6 or 8 characters
    if ([cString length] < 6) return [UIColor blackColor];
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"]) cString = [cString substringFromIndex:1];
    if ([cString length] == 8) {
        [[NSScanner scannerWithString:[cString substringWithRange:range]] scanHexInt:&alpha];
      cString = [cString substringFromIndex:2];
    }
    if ([cString length] != 6) return [UIColor blackColor];
    // Separate into r, g, b substrings

    NSString *rString = [cString substringWithRange:range];
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    // Scan values
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];

    return [UIColor colorWithRed:((float) r / 255.0f)
                           green:((float) g / 255.0f)
                            blue:((float) b / 255.0f)
                           alpha:((float) alpha / 255.0f)];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜