开发者

How do I convert a hex color in an NSString to three separate rgb ints in Objective C?

开发者 https://www.devze.com 2023-04-09 14:29 出处:网络
I may be making something incredibly simple incredibly complicated, but nothing I\'ve tried so far seems to work.

I may be making something incredibly simple incredibly complicated, but nothing I've tried so far seems to work.

I have NSStrings like @"BD8F60" and I would like to turn them into ints like: r = 189, g = 143, b = 96.

Have found ways to conve开发者_开发问答rt hex values that are already ints into rgb ints, but am stuck on how to change the NSString with the letters in it into an int where the letters have been converted to their numerical counterparts. Apologize in advance if this is incredibly basic--I'm still learning this stuff at an incredibly basic level.


You need to parse the NSString and interpret the hex values.

You may do this in multiple ways, one being using an NSScanner

NSScanner* scanner = [NSScanner scannerWithString:@"BD8F60"];
int hex;
if ([scanner scanHexInt:&hex]) {
  // Parsing successful. We have a big int representing the 0xBD8F60 value
  int r = (hex >> 16) & 0xFF; // get the first byte
  int g = (hex >>  8) & 0xFF; // get the middle byte
  int b = (hex      ) & 0xFF; // get the last byte
} else {
  NSLog(@"Parsing error: no hex value found in string");
}

There are some other possibilities like splitting the string in 3 and scan the values separately (instead of doing bitwise shift and masking) but the idea remains the same.

Note: as scanHexInt: documentation explains, this also works if your string is prefixed with 0x like @"0xBD8F60". Does not automatically work with strings prefixed by a hash like @"#BD8F60". Use a substring in this case.


This method turns the given hex-string into a UIColor:

- (UIColor *)colorWithHexString:(NSString *)stringToConvert {
    NSScanner *scanner = [NSScanner scannerWithString:stringToConvert];
    unsigned hex;
    if (![scanner scanHexInt:&hex]) return nil;
    int r = (hex >> 16) & 0xFF;
    int g = (hex >> 8) & 0xFF;
    int b = (hex) & 0xFF;

    return [UIColor colorWithRed:r / 255.0f
                           green:g / 255.0f
                            blue:b / 255.0f
                           alpha:1.0f];
}


a category on UIColor that also deals with alpha values rrggbbaa and short forms as rgb or rgba.

use it it like

UIColor *color = [UIColor colorFromHexString:@"#998997FF"]; //#RRGGBBAA

or

UIColor *color = [UIColor colorFromHexString:@"998997FF"]; //RRGGBBAA

or

UIColor *color = [UIColor colorFromHexString:@"0x998997FF"];// 0xRRGGBBAA

or

UIColor *color = [UIColor colorFromHexString:@"#999"]; // #RGB -> #RRGGBB

or

UIColor *color = [UIColor colorFromHexString:@"#9acd"]; // #RGBA -> #RRGGBBAA

@implementation UIColor (Creation)

+(UIColor *)_colorFromHex:(NSUInteger)hexInt
{
    int r,g,b,a;

    r = (hexInt >> 030) & 0xFF;
    g = (hexInt >> 020) & 0xFF;
    b = (hexInt >> 010) & 0xFF;
    a = hexInt & 0xFF;

    return [UIColor colorWithRed:r / 255.0f
                           green:g / 255.0f
                            blue:b / 255.0f
                           alpha:a / 255.0f];
}

+(UIColor *)colorFromHexString:(NSString *)hexString
{
    hexString = [hexString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if ([hexString hasPrefix:@"#"]) 
        hexString = [hexString substringFromIndex:1];
    else if([hexString hasPrefix:@"0x"])
        hexString = [hexString substringFromIndex:2];

    int l = [hexString length];
    if ((l!=3) && (l!=4) && (l!=6) && (l!=8))
        return nil;

    if ([hexString length] > 2 && [hexString length]< 5) {        
        NSMutableString *newHexString = [[NSMutableString alloc] initWithCapacity:[hexString length]*2];
        [hexString enumerateSubstringsInRange:NSMakeRange(0, [hexString length]) 
                                      options:NSStringEnumerationByComposedCharacterSequences 
                                   usingBlock:^(NSString *substring, 
                                                NSRange substringRange, 
                                                NSRange enclosingRange, 
                                                BOOL *stop) 
        {
            [newHexString appendFormat:@"%@%@", substring, substring];
        }];
        hexString = newHexString;
    }

    if ([hexString length] == 6)
        hexString = [hexString stringByAppendingString:@"ff"];    

    NSScanner *scanner = [NSScanner scannerWithString:hexString];
    unsigned hexNum;
    if (![scanner scanHexInt:&hexNum]) 
        return nil;    
    return [self _colorFromHex:hexNum];
}

@end 

use it in swift:

  • add #include "UIColor+Creation.h" to Bridging Header
  • use

    UIColor(fromHexString:"62AF3C")
    
0

精彩评论

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