I am trying to apply a tint color on a set of UIImages that I have and I came across this neat implementation online that I am trying to understand. My question is about line 2 and line 27. Thanks in advance!
Line 2: What is the syntax in the parameters list? This is something I haven't seen before...
Line 27: This type of return statement is also new to me, I'm guessing its related to the special syntaxt in modifiedImage?
// What is the syntaxt in the parameters list? Never seen this before....
private func modifiedImage( draw: (CGContext, CGRect) -> ()) -> UIImage {
// using scale correctly preserves retina images
UIGraphicsBeginImageContextWithOptions(size, false, scale)
let context: CGContext! = UIGraphicsGetCurrentContext()
assert(context != nil)
// correctly rotate image
context.translateBy(x: 0, y: size.height)
context.scaleBy(x: 1.0, y: -1.0)
let rect = CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height)
draw(context, rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
func tint(tintColor: UIColor) -> UIImage {
// Never seen this type of return statement... maybe if in understand the private func uptop, then
// this will make sense...
return modifiedImage { context, rect in
// draw black background - workaround to preserve color of partially transparent pixels
context.setBlendMode(.normal)
UIColor.black.setFill()
context.fill(rect)
// draw original image
context.setBlendMode(.normal)
context.draw(self.cgImage!, in: rect)
// tint image (loosing alpha) - the luminosity of the original image is preserved
context.setBlendMode(.color)
tintColor.setFill()
context.fill(rect)
// mask by alpha values of original image
context.setBlendMode(.destinationIn)
context.draw(self.cgImage!, in: rect)
}
}