将十六进制颜色字符串转换为无符号长整型

时间:2014-03-11 06:05:47

标签: ios iphone objective-c

+ (UIColor *)colorFromHex:(unsigned long)hex
{
    return [UIColor colorWithRed:((float)((hex & 0xFF0000) >> 16))/255.0 green:((float)((hex & 0xFF00) >> 8))/255.0 blue:((float)(hex & 0xFF))/255.0 alpha:1.0];
}

这是我的功能

我将Color To View设置为如下:

[self.view setBackgroundColor:[UIColor colorFromHex:0x8a32cb]];

现在的问题是:

我在plist文件中从服务器获取颜色代码 和pdColor一样:#8a32cb

我将其分开:

NSString *pdColor;
pdColor = [(NSString *)[temp objectForKey:@"pdColor"] stringByReplacingOccurrencesOfString:@"#" withString:@"0x"];

pdCOlor采用字符串格式。 我需要在这里申请:

[self.view setBackgroundColor:[UIColor colorFromHex:pdColor]];

但它是无符号长的,所以它没有得到正确的颜色代码。

请帮我解决这个问题。

4 个答案:

答案 0 :(得分:2)

您不需要stringByReplacingOccurrencesOfString。 十六进制字符串可以转换为strtoul()的数字。注意用法 + 1跳过最初的"#字符:

NSString *pdColor = [temp objectForKey:@"pdColor"]; // The string "#8a32cb"
unsigned long color = strtoul([pdColor UTF8String] + 1, NULL, 16);
[self.view setBackgroundColor:[UIColor colorFromHex:color]];

答案 1 :(得分:0)

请测试我的答案。您将在此处获得准确的结果。

NSScanner *scanner2 = [NSScanner scannerWithString:pdColor];
unsigned baseColor1;
[scanner2 scanHexInt:&baseColor1];
CGFloat red   = ((baseColor1 & 0xFF0000) >> 16) / 255.0f;
CGFloat green = ((baseColor1 & 0x00FF00) >>  8) / 255.0f;
CGFloat blue  =  (baseColor1 & 0x0000FF) / 255.0f;
[self.view setBackgroundColor:[UIColor colorWithRed:red green:green blue:blue alpha:1.0]];

答案 2 :(得分:0)

使用这些方法

-(UIColor *) colorWithHexString: (NSString *) hexString {
    NSString *colorString = [[hexString stringByReplacingOccurrencesOfString: @"#" withString: @""] uppercaseString];
    CGFloat alpha, red, blue, green;
    alpha = 1.0f;
    red   = [self colorComponentFrom: colorString start: 0 length: 2];
    green = [self colorComponentFrom: colorString start: 2 length: 2];
    blue  = [self colorComponentFrom: colorString start: 4 length: 2];
    return [UIColor colorWithRed: red green: green blue: blue alpha: alpha];
}


-(CGFloat) colorComponentFrom: (NSString *) string start: (NSUInteger) start length: (NSUInteger) length {
    NSString *substring = [string substringWithRange: NSMakeRange(start, length)];
    NSString *fullHex = length == 2 ? substring : [NSString stringWithFormat: @"%@%@", substring, substring];
    unsigned hexComponent;
    [[NSScanner scannerWithString: fullHex] scanHexInt: &hexComponent];
    return hexComponent / 255.0;
}

只需将十六进制字符串例如@“#8a32cb”传递给第一个方法,它将返回UICOLOR

希望这会对你有所帮助。

答案 3 :(得分:0)

NSString *pdColor =[[temp objectForKey:@"pdColor"] stringByReplacingOccurrencesOfString:@"#" withString:@""];
NSScanner* scanner = [NSScanner scannerWithString:pdColor];
unsigned int hex;
[scanner scanHexInt:&hex];
UIColor *color = [UIColor colorFromHex:hex];