Skip to content

Instantly share code, notes, and snippets.

@wess
Created June 29, 2015 15:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wess/ddb9ca50f3ce19298a01 to your computer and use it in GitHub Desktop.
Save wess/ddb9ca50f3ce19298a01 to your computer and use it in GitHub Desktop.
- (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