如何将RGB整数转换为相应的RGB元组(R,G,B)?

时间:2010-08-18 06:45:37

标签: objective-c c

如何将ARGB整数转换为相应的ARGB元组(A,R,G,B)?

我收到一些XML,其中颜色标签带有一些整数值(例如-16777216)。我需要画一个用这种颜色填充的矩形。但是我无法从整数值中检索A,R,G,B组件的值。

4 个答案:

答案 0 :(得分:3)

如果整数是ARGB,我认为它应该是:

unsigned char b = color & 0x000000FF;
unsigned char g = (color>> 8) & 0x000000FF;
unsigned char r = (color>>16) & 0x000000FF;
unsigned char a = (color>>24) & 0x000000FF;

答案 1 :(得分:2)

使用按位AND和右移从32位整数中选择单个字节。

uint32_t color = -16777216;

uint8_t b = (color & 0x000000ff);
uint8_t g = (color & 0x0000ff00) >> 8;
uint8_t r = (color & 0x00ff0000) >> 16;
uint8_t a = (color & 0xff000000) >> 24;

答案 2 :(得分:1)

您可以尝试使用工会。像这样的东西

struct color
{
  unsigned char alpha:8;
  unsigned char r:8;
  unsigned char g:8;
  unsigned char b:8;
};

union
{
  struct color selector;
  unsigned int base:32;
};

答案 3 :(得分:0)

请尝试以下代码:

unsigned a = (color >> 24) & 0x000000FF;
unsigned b = (color >> 16) & 0x000000FF;
unsigned g = (color >> 8) & 0x000000FF;
unsigned r = color & 0x000000FF;

CGFloat rf = (CGFloat)r / 255.f;
CGFloat gf = (CGFloat)g / 255.f;
CGFloat bf = (CGFloat)b / 255.f;
CGFloat af = (CGFloat)a / 255.f;