Swift - 使用CGBlendMode改变UIImage颜色

类似于PS,Swift中也可对图片UIImage进行图层混合(blending),而且提供了相当丰富的混合模式(blendMode)。本文先介绍使用其中的kCGBlendModeDestinationIn实现图片颜色的修改。

1,扩展UIImage,添加着色方法
首先为便于blending,我们扩展系统UIImage类,给其增加tint方法,方法内部即为相关的图层混合操作。

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变可以满足这个需求。

直接上代码如下

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()
    }
}

你可能感兴趣的:(图片,PS,swift,uiimage)