How can I convert an RGB integer to the corresponding RGB tuple (R,G,B)?
How can I convert an ARGB integer to the corresponding ARGB tuple (A,R,G,B)?
I receive some XML where a color tag is given with some integer value (e.g -16777216). I need to draw a rectangle filled with that color. But I am unable to retrieve values of the A,R,G,B components from the intege开发者_StackOverflow社区r value.
If the integer is ARGB I think it should be:
unsigned char b = color & 0x000000FF;
unsigned char g = (color>> 8) & 0x000000FF;
unsigned char r = (color>>16) & 0x000000FF;
unsigned char a = (color>>24) & 0x000000FF;
Use bitwise AND and shift right to select individual bytes from the 32-bit integer.
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;
You can try use unions. Something like this
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;
};
Try the following code:
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;
精彩评论