Skip to content

Instantly share code, notes, and snippets.

@yong076
Forked from lynfogeek/UIImage+Colorize.swift
Last active August 8, 2018 06:17
Show Gist options
  • Save yong076/f5744dd5820dc7f132b0985d521611ca to your computer and use it in GitHub Desktop.
Save yong076/f5744dd5820dc7f132b0985d521611ca to your computer and use it in GitHub Desktop.
import UIKit
extension UIImage {
func tint(tintColor: UIColor) -> UIImage {
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)
}
}
// fills the alpha channel of the source image with the given color
// any color information except to the alpha channel will be ignored
func fillAlpha(fillColor: UIColor) -> UIImage {
return modifiedImage { context, rect in
// draw tint color
context.setBlendMode(.normal)
fillColor.setFill()
context.fill(rect)
// context.fillCGContextFillRect(context, rect)
// mask by alpha values of original image
context.setBlendMode(.destinationIn)
context.draw(self.cgImage!, in: rect)
}
}
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!
}
}
extension UIImageView {
func playBounceAnimation() {
let bounceAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
bounceAnimation.values = [1.0, 1.1, 0.9, 1.05, 0.95, 1.02, 1.0]
bounceAnimation.duration = TimeInterval(0.5)
bounceAnimation.calculationMode = kCAAnimationCubic
self.layer.add(bounceAnimation, forKey: nil)
if let iconImage = self.image {
let renderImage = iconImage.withRenderingMode(.alwaysTemplate)
self.image = renderImage
self.tintColor = BBBlackColor
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment