//
// UIImage+Extension.swift
// ChatBubbleProject
//
// Created by 周辉 on 2017/5/16.
// Copyright © 2017年 周辉. All rights reserved.
//
import Foundation
import UIKit
import QuartzCore
import Accelerate
extension UIImage {
func blurredImage(radius: CGFloat, iterations: Int, tintColor: UIColor) -> UIImage {
if floor(size.width) * floor(size.height) <= 0.0 {
return self
}
var boxSize = UInt32(radius * scale)
if boxSize % 2 == 0 {
boxSize += 1
}
var imageRef = cgImage
if imageRef?.bitsPerPixel != 32 ||
imageRef?.bitsPerComponent != 8 ||
!(imageRef?.bitmapInfo.contains(CGBitmapInfo.alphaInfoMask))! {
UIGraphicsBeginImageContextWithOptions(size, false, scale)
draw(at: .zero)
imageRef = UIGraphicsGetImageFromCurrentImageContext()?.cgImage
UIGraphicsEndImageContext()
}
var buffer1 = vImage_Buffer()
var buffer2 = vImage_Buffer()
buffer1.width = UInt((imageRef?.width)!)
buffer2.width = UInt((imageRef?.width)!)
buffer1.height = UInt((imageRef?.height)!)
buffer2.height = UInt((imageRef?.height)!)
buffer1.rowBytes = (imageRef?.bytesPerRow)!
buffer2.rowBytes = (imageRef?.bytesPerRow)!
let bytes = buffer1.rowBytes * Int(buffer1.height)
buffer1.data = malloc(bytes)
buffer2.data = malloc(bytes)
if buffer1.data == nil || buffer2.data == nil {
free(buffer1.data)
free(buffer2.data)
return self
}
let tempBuffer = malloc(vImageBoxConvolve_ARGB8888(&buffer1,
&buffer2,
nil, 0, 0,
boxSize, boxSize, nil,
vImage_Flags(kvImageEdgeExtend+kvImageGetTempBufferSize)))
let provider = imageRef?.dataProvider
let dataSource = provider?.data
if dataSource == nil {
return self
}
let dataSourceData = CFDataGetBytePtr(dataSource)
let dataSourceLength = CFDataGetLength(dataSource)
memcpy(buffer1.data, dataSourceData, min(bytes, dataSourceLength))
// CFRelease(dataSource) // CF 现在也在 ARC 的管辖范围之内,见http://swifter.tips/
for _ in 0..<iterations {
vImageBoxConvolve_ARGB8888(&buffer1,
&buffer2,
tempBuffer,
0, 0, boxSize, boxSize,
nil, vImage_Flags(kvImageEdgeExtend))
swap(&buffer1.data, &buffer2.data)
}
free(buffer2.data)
free(tempBuffer)
let ctx = CGContext.init(data: buffer1.data,
width: Int(buffer1.width),
height: Int(buffer1.height),
bitsPerComponent: 8,
bytesPerRow: buffer1.rowBytes,
space: (imageRef?.colorSpace)!,
bitmapInfo: (imageRef?.bitmapInfo.rawValue)!)
if tintColor.cgColor.alpha > 0.0 {
ctx?.setFillColor(tintColor.withAlphaComponent(0.25).cgColor)
ctx?.setBlendMode(.plusLighter)
ctx?.fill(CGRect(x: 0, y: 0, width: Int(buffer1.width), height: Int(buffer1.height)))
}
imageRef = ctx?.makeImage()
let image = UIImage(cgImage: imageRef!, scale: scale, orientation: imageOrientation)
free(buffer1.data)
return image
}
}
🍜食用
class ViewController: UIViewController {
let blurImageView: UIImageView = {
let iv = UIImageView()
iv.image = UIImage(named: "twg")?.blurredImage(radius: 0, iterations: 0, tintColor: UIColor.white)
return iv
}()
}
🐶效果