在iOS中将字符串转换为十六进制?

时间:2013-06-12 07:51:59

标签: ios xcode string hex

我基本上是让用户在UITextField中输入十六进制值并将其写入字符串以用于颜色选择(教育目的)。如何将字符串转换为十六进制?

2 个答案:

答案 0 :(得分:1)

我不确定这是否是你想要的场景......看看这是否有用..

通过传递hexstring来调用第一个方法,作为回报,你将获得UIColor

- (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;
}

答案 1 :(得分:0)

嗨,这是一个很好的例子:

+ (UIColor *) colorFromHexString:(NSString *)hexString {
NSString *cleanString = [hexString stringByReplacingOccurrencesOfString:@"#" withString:@""];
if([cleanString length] == 3) {
    NSString *red = [cleanString substringWithRange:NSMakeRange(0, 1)];
    NSString *green = [cleanString substringWithRange:NSMakeRange(1, 1)];
    NSString *blue = [cleanString substringWithRange:NSMakeRange(2, 1)];
    cleanString = [NSString stringWithFormat:@"ff%1$@%1$@%2$@%2$@%3$@%3$@", red, green, blue];
}else if([cleanString length] == 6) {
    cleanString = [@"ff" stringByAppendingString:cleanString];
}else{
    //do nothing
}

NSLog(@"%@", cleanString);

unsigned int rgba;
[[NSScanner scannerWithString:cleanString] scanHexInt:&rgba];

CGFloat alpha = ((rgba & 0xFF000000) >> 24) / 255.0f;
CGFloat red = ((rgba & 0x00FF0000) >> 16) / 255.0f;
CGFloat green = ((rgba & 0x0000FF00) >> 8) / 255.0f;
CGFloat blue = (rgba & 0x000000FF) / 255.0f;

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

}

您也可以在我的博客hrupin.com

中看到它