如何将 NSString 中的十六进制颜色转换为 Objective C 中的三个单独的 rgb 整数?

发布于 2024-12-07 19:53:53 字数 240 浏览 2 评论 0原文

我可能正在把一些非常简单的事情变得非常复杂,但到目前为止我所尝试的一切似乎都不起作用。

我有像@“BD8F60”这样的NSString,我想将它们转换为整数,例如:r = 189,g = 143,b = 96。

已经找到了将已经是整数的十六进制值转换为rgb整数的方法,但我坚持下去如何将包含字母的 NSString 更改为 int,其中字母已转换为对应的数字。如果这是非常基础的,请提前道歉——我仍然在非常基础的水平上学习这些东西。

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 convert 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

独享拥抱 2024-12-14 19:53:53

您需要解析 NSString 并解释十六进制值。

您可以通过多种方式执行此操作,其中一种是使用 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");
}

还有其他一些可能性,例如将字符串拆分为 3 部分并分别扫描值(而不是进行按位移位和屏蔽),但想法保持不变。

注意:正如 scanHexInt: 文档所解释的,如果您的字符串以 0x 为前缀(如 @"0xBD8F60"),这也适用。不会自动处理以哈希为前缀的字符串,例如 @"#BD8F60"。在这种情况下使用子字符串。

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.

宁愿没拥抱 2024-12-14 19:53:53

此方法将给定的十六进制字符串转换为 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];
}

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];
}
⒈起吃苦の倖褔 2024-12-14 19:53:53

UIColor 上的一个类别,还处理 alpha 值 rrggbbaa 和缩写形式如 rgb 或 rgba。

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

或或

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

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

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

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 

swift 中使用它:

  • 添加 #include "UIColor+Creation.h" 到桥接头
  • use

    UIColor(fromHexString:"62AF3C")
    

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")
    
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文