Created
June 29, 2015 15:17
-
-
Save wess/ddb9ca50f3ce19298a01 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (UIColor *)colorByChangingAlphaTo:(CGFloat)alpha | |
{ | |
CGFloat *oldComponents = (CGFloat *)CGColorGetComponents([self CGColor]); | |
size_t numComponents = CGColorGetNumberOfComponents([self CGColor]); | |
CGFloat newComponents[4]; | |
switch (numComponents) | |
{ | |
case 2: | |
{ | |
//grayscale | |
newComponents[0] = oldComponents[0]; | |
newComponents[1] = oldComponents[0]; | |
newComponents[2] = oldComponents[0]; | |
newComponents[3] = alpha; | |
break; | |
} | |
case 4: | |
{ | |
//RGBA | |
newComponents[0] = oldComponents[0]; | |
newComponents[1] = oldComponents[1]; | |
newComponents[2] = oldComponents[2]; | |
newComponents[3] = alpha; | |
break; | |
} | |
} | |
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); | |
CGColorRef newColor = CGColorCreate(colorSpace, newComponents); | |
CGColorSpaceRelease(colorSpace); | |
UIColor *color = [UIColor colorWithCGColor:newColor]; | |
CGColorRelease(newColor); | |
return color; | |
} | |
- (UIColor *)invertColor | |
{ | |
CGColorRef oldCGColor = self.CGColor; | |
size_t numberOfComponents = CGColorGetNumberOfComponents(oldCGColor); | |
if (numberOfComponents == 1) | |
return [UIColor colorWithCGColor:oldCGColor]; | |
const CGFloat *oldComponentColors = CGColorGetComponents(oldCGColor); | |
CGFloat newComponentColors[numberOfComponents]; | |
NSInteger i = numberOfComponents - 1; | |
newComponentColors[i] = oldComponentColors[i]; | |
while (--i >= 0) | |
newComponentColors[i] = 1 - oldComponentColors[i]; | |
CGColorRef newCGColor = CGColorCreate(CGColorGetColorSpace(oldCGColor), newComponentColors); | |
UIColor *newColor = [UIColor colorWithCGColor:newCGColor]; | |
CGColorRelease(newCGColor); | |
return newColor; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment