This is pretty much the answer above, but slightly shortened. It only perceives the image as a mask and actually does not โreproduceโ and does not color the image.
Goal C:
UIColor *color = <# UIColor #>; UIImage *image = <# UIImage #>;// Image to mask with UIGraphicsBeginImageContextWithOptions(image.size, NO, image.scale); CGContextRef context = UIGraphicsGetCurrentContext(); [color setFill]; CGContextTranslateCTM(context, 0, image.size.height); CGContextScaleCTM(context, 1.0, -1.0); CGContextClipToMask(context, CGRectMake(0, 0, image.size.width, image.size.height), [image CGImage]); CGContextFillRect(context, CGRectMake(0, 0, image.size.width, image.size.height)); UIImage *coloredImg = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext();
Swift:
let color: UIColor = <# UIColor #> let image: UIImage = <# UIImage #> // Image to mask with UIGraphicsBeginImageContextWithOptions(image.size, false, image.scale) let context = UIGraphicsGetCurrentContext() color.setFill() context?.translateBy(x: 0, y: image.size.height) context?.scaleBy(x: 1.0, y: -1.0) context?.clip(to: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height), mask: image.cgImage!) context?.fill(CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)) let coloredImg = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext()
user1270061 03 Oct '13 at 6:57 2013-10-03 06:57
source share