类似于PS,Swift中也可对图片UIImage进行图层混合(blending),而且提供了相当丰富的混合模式(blendMode)。本文先介绍使用其中的kCGBlendModeDestinationIn实现图片颜色的修改。
首先为便于blending,我们扩展系统UIImage类,给其增加tint方法,方法内部即为相关的图层混合操作。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
import UIKit//--- UIImageTintExtension.swift ---extension UIImage{ func tint(color: UIColor, blendMode: CGBlendMode) -> UIImage { let drawRect = CGRectMake(0.0, 0.0, size.width, size.height) UIGraphicsBeginImageContextWithOptions(size, false, scale) //let context = UIGraphicsGetCurrentContext() //CGContextClipToMask(context, drawRect, CGImage) color.setFill() UIRectFill(drawRect) drawInRect(drawRect, blendMode: blendMode, alpha: 1.0) let tintedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return tintedImage }} |

|
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
|
import UIKitclass ViewController: UIViewController { //用于显示原图 @IBOutlet weak var imageView0: UIImageView! //用于显示处理后的图片 @IBOutlet weak var imageView1: UIImageView! @IBOutlet weak var imageView2: UIImageView! @IBOutlet weak var imageView3: UIImageView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //设置原图 imageView0.image=UIImage(named:"logo6") //设置各种色调的图片 imageView1.image = UIImage(named:"logo6")?.tint(UIColor.brownColor(), blendMode: .DestinationIn) imageView2.image = UIImage(named:"logo6")?.tint(UIColor.blueColor(), blendMode: .DestinationIn) imageView3.image = UIImage(named:"logo6")?.tint(UIColor.orangeColor(), blendMode: .DestinationIn) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() }} |
Swift - 使用CGBlendMode改变UIImage颜色
原文:http://www.cnblogs.com/Free-Thinker/p/4843877.html