Last active
August 29, 2015 13:59
-
-
Save gbarcena/10937995 to your computer and use it in GitHub Desktop.
Adds a masked colored border to an image
This file contains 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
- (UIImage *)applyBorderColor:(UIColor *)color toImage:(UIImage*)toImage{ | |
UIGraphicsBeginImageContextWithOptions(toImage.size, NO, toImage.scale); | |
CGContextRef context = UIGraphicsGetCurrentContext(); | |
CGContextTranslateCTM(context, 0, toImage.size.height); | |
CGContextScaleCTM(context, 1.0, -1.0); | |
CGContextSetBlendMode(context, kCGBlendModeNormal); | |
CGRect rect = CGRectMake(0, 0, toImage.size.width, toImage.size.height); | |
// Create gradient | |
NSArray *colors = [NSArray arrayWithObjects:(id)color.CGColor, (id)color.CGColor, nil]; | |
CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB(); | |
CGGradientRef gradient = CGGradientCreateWithColors(space, (__bridge CFArrayRef)colors, NULL); | |
// Apply gradient | |
CGContextClipToMask(context, rect, toImage.CGImage); | |
CGContextDrawLinearGradient(context, gradient, CGPointMake(0,0), CGPointMake(0, toImage.size.height), 0); | |
// Draw the original image | |
CGFloat difference = 30.0f; | |
CGSize size = [toImage size]; | |
CGContextTranslateCTM(context, 0, toImage.size.height); | |
CGContextScaleCTM(context, 1.0, -1.0); | |
CGRect smallerRect = CGRectMake(difference, difference, size.width - difference*2, size.height - difference*2); | |
[toImage drawInRect:smallerRect]; | |
UIImage *coloredImage = UIGraphicsGetImageFromCurrentImageContext(); | |
UIGraphicsEndImageContext(); | |
CGGradientRelease(gradient); | |
CGColorSpaceRelease(space); | |
return coloredImage; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment