类似于PS,Swift中也可对图片UIImage进行图层混合(blending),而且提供了相当丰富的混合模式(blendMode)。本文先介绍使用其中的kCGBlendModeDestinationIn实现图片颜色的修改。
1,扩展UIImage,添加着色方法
首先为便于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
}
}
|
2,改变图片的颜色
有时我们的App需要能切换不同的主题和场景,希望图片能动态的改变颜色以配合对应场景的色调。虽然我们可以根据不同主题事先创建不同颜色的图片供调用,但既然用的图片素材都一样,还一个个转换显得太麻烦,而且不便于维护。使用blendMode变可以满足这个需求。
(1)效果图如下
可以看到最上面的一个是原图,下面三个是通过代码动态的改变颜色(透明度什么的都很好的保存了)
![](https://i-blog.csdnimg.cn/blog_migrate/16785dd1dfa7d714e845d45ad6a9c3df.png)
(2)代码如下
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
UIKit
class
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()
}
}
|