使用 vImage 生成高斯模糊图像,ObjC -> Swift 4,翻译自 iOS开发探索-高斯模糊&毛玻璃效果

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
private func vBlurImage(_ image: UIImage, blurNumber blur: Float) -> UIImage {
var blur = blur
if blur < 0.0 || blur > 1.0 {
blur = 0.5
}
var boxSize = Int(blur * 40)
boxSize = boxSize - (boxSize % 2) + 1

let img = image.cgImage!

var inBuffer = vImage_Buffer()
var outBuffer = vImage_Buffer()
var error: vImage_Error!
var pixelBuffer: UnsafeMutableRawPointer?

// 从CGImage中获取数据
let inProvider = img.dataProvider!
let inBitmapData = inProvider.data!

// 设置从CGImage获取对象的属性
inBuffer.width = UInt(img.width)
inBuffer.height = UInt(img.height)
inBuffer.rowBytes = img.bytesPerRow
inBuffer.data = UnsafeMutableRawPointer(mutating: CFDataGetBytePtr(inBitmapData))
pixelBuffer = malloc(img.bytesPerRow * img.height)
if pixelBuffer == nil {
print("No pixel buffer!")
}

outBuffer.data = pixelBuffer
outBuffer.width = UInt(img.width)
outBuffer.height = UInt(img.height)
outBuffer.rowBytes = img.bytesPerRow

error = vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, nil, 0, 0, UInt32(boxSize), UInt32(boxSize), nil, UInt32(kvImageEdgeExtend))
if error != nil && error != 0 {
print("error from convolution \(error)")
}

let colorSpace = CGColorSpaceCreateDeviceRGB()
let ctx = CGContext(data: outBuffer.data, width: Int(outBuffer.width), height: Int(outBuffer.height), bitsPerComponent: 8, bytesPerRow: outBuffer.rowBytes, space: colorSpace, bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)

let imageRef = ctx!.makeImage()!
let returnImage = UIImage(cgImage: imageRef)

return(pixelBuffer)

return returnImage
}

参考