Skip to content

Instantly share code, notes, and snippets.

@iwill
Created May 5, 2011 17:30
Show Gist options
  • Save iwill/957471 to your computer and use it in GitHub Desktop.
Save iwill/957471 to your computer and use it in GitHub Desktop.
Objective-C UIColor - inverseColor
//
// UIColor+.h
// iTest
//
// Created by iwill on 11-03-09.
// Copyright 2011 iwill. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface UIColor (plus)
- (UIColor *) inverseColor;
@end
//
// UIColor+.m
// iMSC
//
// Created by iwill on 11-03-09.
// Copyright 2011 iwill. All rights reserved.
//
#import "UIColor+.h"
@implementation UIColor (plus)
- (UIColor *) inverseColor {
CGColorRef oldCGColor = self.CGColor;
int numberOfComponents = CGColorGetNumberOfComponents(oldCGColor);
// can not invert - the only component is the alpha
// e.g. self == [UIColor groupTableViewBackgroundColor]
if (numberOfComponents <= 1) {
return [UIColor colorWithCGColor:oldCGColor];
}
const CGFloat *oldComponentColors = CGColorGetComponents(oldCGColor);
CGFloat newComponentColors[numberOfComponents];
int i = - 1;
while (++i < numberOfComponents - 1) {
newComponentColors[i] = 1 - oldComponentColors[i];
}
newComponentColors[i] = oldComponentColors[i]; // alpha
CGColorRef newCGColor = CGColorCreate(CGColorGetColorSpace(oldCGColor), newComponentColors);
UIColor *newColor = [UIColor colorWithCGColor:newCGColor];
CGColorRelease(newCGColor);
return newColor;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment