Skip to content

Instantly share code, notes, and snippets.

@imxieyi
Created August 1, 2017 18:46
Show Gist options
  • Save imxieyi/dde9fd713e88c24145c0bf8d3f2ba057 to your computer and use it in GitHub Desktop.
Save imxieyi/dde9fd713e88c24145c0bf8d3f2ba057 to your computer and use it in GitHub Desktop.
Directly blend image in UIImageView with specific color in XCode Interface Builder
import UIKit
@IBDesignable
open class BlendImageView:UIImageView {
@IBInspectable open var color:UIColor? {
didSet {
if self.image != nil {
self.image = self.image?.image(withTint: color!)
}
}
}
@IBInspectable open var blendAlpha:CGFloat = 1 {
didSet {
if self.image != nil && self.color != nil {
self.image = self.image?.image(withTint: color!, blendAlpha: alpha, blendMode: .destinationIn)
}
}
}
}
extension UIImage {
//Reference: https://onevcat.com/2013/04/using-blending-in-ios/
open func image(withTint color:UIColor, blendAlpha alpha:CGFloat, blendMode mode:CGBlendMode) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, 0)
color.setFill()
let bounds = CGRect(origin: .zero, size: size)
UIRectFill(bounds)
draw(in: bounds, blendMode: mode, alpha: alpha)
let tinted = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return tinted!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment