Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ios Convert integer color to uicolor or hex values?

In android there is an option where you can set color based on int value. Is there anyway that I can use this value or convert this value to set it as UIColor in iOS? For example this value, -5242884 can be used in android to set color.

From what I managed to find is that iOS widely use hex value or rgb value to set for UIColor. But I couldn't find any info regarding about my issue here. Is there anyway around that I can use int value instead.

like image 335
IssacZH. Avatar asked Sep 12 '25 21:09

IssacZH.


1 Answers

It appears that the integer number to which you are referencing is a packed integer. See: android color documentation. You need to find a way to convert the packed int to a hex and then you can use this macro (obtained here) which converts a hex number to UIColor:

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

I know this doesn't really answer your question but it may help you narrow down your search.

Edit

Ok so I just realized the above macro does solve your problem. Just give it the integer representation and it will give you the right UIColor. My test code is below:

UIColor *color = HEXCOLOR(-16776961); // Blue const from android link above
const CGFloat *components = CGColorGetComponents(color.CGColor);
NSString *colorAsString = [NSString stringWithFormat:@"%f,%f,%f,%f", components[0], components[1], components[2], components[3]]; 
NSLog(@"%@",colorAsString); // Prints 1.0 0.0 0.0 1.0 which corresponds to 0xff0000ff

I had some help from here.

Edit

Fixed the macro to expect the correct RGBA values:

#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]

The previous macro expected RGBA while the Android color int gave ARGB.

like image 117
nalyd88 Avatar answered Sep 15 '25 10:09

nalyd88