直接在XCode Interface Builder中混合图片颜色

iOS UIKit中的UIImageView用于显示一张图片,然而它不支持颜色混合。有些时候我们希望同一张图片在不同地方显示不同颜色,这样就只能通过代码实现。事实上,通过一个小小的扩展就能轻松实现直接在Interface Builder中修改图片颜色。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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!
}

}

使用方法很简单,直接在UIImaveView的Class中指定BlendImageView,然后就会出现Color和Alpha的选项,修改后还能实时显示结果。

文章目录
|