如何在目标C中将NSString中的十六进制颜色转换为三个独立的rgb int? [英] How do I convert a hex color in an NSString to three separate rgb ints in Objective C?

查看:214
本文介绍了如何在目标C中将NSString中的十六进制颜色转换为三个独立的rgb int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可能正在做一些令人难以置信的简单令人难以置信的复杂,但没有我试过迄今似乎工作。

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

我有NSStrings像@BD8F60想要将它们转换为int类似:r = 189,g = 143,b = 96。

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

找到了方法来将已经是int的十六进制值转换为rgb int ,但是我坚持如何改变NSString中的字母到一个int,其中字母已被转换为其数字对应。

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.

推荐答案

你需要的是一个令人难以置信的基础。解析NSString并解析十六进制值。

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

您可以通过多种方式来实现,一种是使用NSScanner

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");
}

还有一些其他可能性,例如在3中分割字符串并分别扫描值

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.

注意: scanHexInt:文档说明,如果你的字符串以 0x 为前缀,如 @0xBD8F60不自动使用以 @#BD8F60为前缀的字符串。在这种情况下使用子字符串。

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.

这篇关于如何在目标C中将NSString中的十六进制颜色转换为三个独立的rgb int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆