Created
August 1, 2017 18:46
-
-
Save imxieyi/dde9fd713e88c24145c0bf8d3f2ba057 to your computer and use it in GitHub Desktop.
Directly blend image in UIImageView with specific color in XCode Interface Builder
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
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