2

I have gotten pretty far in mobile development figuring things out on my own, but I'm having a lot of trouble figuring this one out...

I am converting Android color (packed int) to UIColor using this macro:

#define ANDROID_COLOR(c) [UIColor colorWithRed:((c>>16)&0xFF)/255.0 green:((c>>8)&0xFF)/255.0 blue:((c)&0xFF)/255.0  alpha:((c>>24)&0xFF)/255.0]

However I also need to convert a UIColor to Android colour. Any help is very much appreciated!

user2651293
  • 65
  • 1
  • 6
  • See http://stackoverflow.com/questions/21608422/getting-rgb-values-from-uicolors-derived-from-hex-colors/21608716#21608716 to get the RGB values from `UIColor`. Once you have those, reverse what you did above to create the packed int. – rmaddy Mar 16 '14 at 01:18
  • Getting the RGBA values is fine, but the part I'm having trouble with is converting that to the packed int. I would post the code that I have tried but I've been screwing around with it for hours... – user2651293 Mar 16 '14 at 01:49

1 Answers1

8

Something like this (untested) should work:

UIColor *color =  // your color
CGFloat red, green, blue, alpha;

if (![color getRed:&red green:&green blue:&blue alpha:&alpha]) {

    CGFloat white;
    if ([color getWhite:&white alpha:&alpha]) {
        red = green = blue = white;
    } else {
        NSLog(@"Uh oh, not RGB or greyscale");
    }
}

long r = red * 255;
long g = green * 255;
long b = blue * 255;
long a = alpha * 255;
long packed_color = (r << 16) | (g << 8) | (b) | (a << 24);

That appears to be the reverse of what you showed in your question.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • When I first implemented your code, and had the same erroneous results as I was having previously. It turned out I was saving my packed int as a string with NSDefaults and retrieving it as an integer, and that was the real source of my confusion. In the end your answer helped solve my problem, and now this code is here to help someone else. – user2651293 Mar 16 '14 at 02:52