Lutz Vegas
Lutz Vegas

Reputation: 23

Converting a String to Hex in iOS?

I'm basically letting the user enter a hexadecimal value in a UITextField and write it into a string to use it for color picking (educational purpose). How do i convert a string to hex?

Upvotes: 2

Views: 1275

Answers (2)

ihrupin
ihrupin

Reputation: 6972

Hi here is good example:

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

}

Also you can see it in my blog hrupin.com

Upvotes: 1

Prashant Nikam
Prashant Nikam

Reputation: 2251

I am not sure if this is what u want in your scenario...see if this is useful or not..

call first method by passing the hexstring and in return u will get the 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;
}

Upvotes: 2

Related Questions