HEX到UIColorfromRGB

时间:2011-04-06 08:35:07

标签: iphone objective-c uicolor

我正在关注教程here

这很简单,只有两个步骤。但是在最后一步,我在UITextField中将HEX代码作为hexText.text,但是我如何将它放入UIColorFromRGB?

3 个答案:

答案 0 :(得分:2)

here是一种避免宏观内容的解决方案。您可以将它添加到UIColor的类别中并更好地使用它。

答案 1 :(得分:0)

我认为,索林在这里有正确的想法。更像可可,会导致更少的头痛。要在较高级别回答您的问题,您需要将字符串转换为十六进制数,然后将结果值传递给宏。我认为只要将字符串值传递到Sorin链接中列出的类别,您就会更好。

答案 2 :(得分:0)

这将解决任何情况

+ (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)];
}