我們有時(shí)候需要給圖片上繪制一層渲染色,雖然可以在控件上添加一層視圖袜硫,但是這種做法效率很低冲簿,不如直接把圖片繪制為帶有渲染色的圖片來(lái)得好
代碼:
func tintedImageWithColor(color: UIColor, originalityImage: UIImage!) -> UIImage {
//創(chuàng)建圖片位置大小
let imageRect = CGRect(x: 0.0, y: 0.0, width: originalityImage.size.width, height: originalityImage.size.height)
//設(shè)置繪制圖片上下文
UIGraphicsBeginImageContextWithOptions(imageRect.size, false, originalityImage.scale)
//得到上下文
let context = UIGraphicsGetCurrentContext()
//繪制圖片
originalityImage.drawInRect(imageRect)
//設(shè)置渲染顏色
CGContextSetFillColorWithColor(context, color.CGColor)
//設(shè)置透明度(值可根據(jù)需求更改)
CGContextSetAlpha(context, 0.5)
//設(shè)置混合模式
CGContextSetBlendMode(context, CGBlendMode.SourceAtop)
//設(shè)置位置大小
CGContextFillRect(context, imageRect)
//繪制圖片
let imageRef = CGBitmapContextCreateImage(context)
let darkImage = UIImage(CGImage: imageRef!, scale: originalityImage.scale, orientation: originalityImage.imageOrientation)
//完成繪制
UIGraphicsEndImageContext()
return darkImage
}
來(lái)使用一下吧
let imageView = UIImageView(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
view.addSubview(imageView)
let image = UIImage(named: "crab.JPG")
imageView.image = image
原圖如下:
Simulator Screen Shot 2016年4月23日 下午5.55.15.png
設(shè)置圖片渲染色后:
var image = UIImage(named: "crab.JPG")
image = tintedImageWithColor(UIColor.greenColor(), originalityImage: image)
imageView.image = image
效果如下:
Simulator Screen Shot 2016年4月23日 下午5.59.06.png