Skip to content

Instantly share code, notes, and snippets.

@dduan
Last active August 29, 2015 13:55
Show Gist options
  • Save dduan/8736115 to your computer and use it in GitHub Desktop.
Save dduan/8736115 to your computer and use it in GitHub Desktop.
A category that converts UIColor to int32_t for convenient persistence.
//
// UIColor+SingleValue.h
//
// Created by Daniel Duan on 1/26/14.
// BSD License
//
#import <UIKit/UIKit.h>
@interface UIColor (SingleValue)
- (UIColor *)initWithInteger: (int32_t)integer;
- (int32_t)integerValue;
@end
//
// UIColor+SingleValue.m
//
// Created by Daniel Duan on 1/26/14.
// BSD License
//
// Represent a RGBA color in 32 bit int
// Using data generated / stored this way across platform might cause issue due to endian difference.
#import "UIColor+IntegerValue.h"
@implementation UIColor (IntegerValue)
- (UIColor *)initWithInteger: (int32_t)integer
{
if (self) {
self = [self initWithRed:(float)((integer >> 24) & 255) / 255
green:(float)((integer >> 16) & 255) / 255
blue:(float)((integer >> 8 ) & 255) / 255
alpha:(float)( integer & 255) / 255];
}
return self;
}
- (int32_t)integerValue
{
CGFloat r, g, b, a;
if (self) {
[self getRed: &r green: &g blue: &b alpha: &a];
return (((int)(r * 255)) << 24) ^ (((int)(g * 255)) << 16) ^ (((int)(b * 255)) << 8) ^ (int)(a * 255);
} else {
return 0;
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment