//MARK: UImage
extensionUIImage{
//增加模糊的效果(需要添加Accelerate.Framework)
funcgaosiBlur(blur:Double) ->UIImage{
varblurAmount = blur
//高斯模糊参数(0-1)之间,超出范围强行转成0.5
if(blurAmount <0.0||blurAmount >1.0) {
blurAmount =0.5
}
varboxSize =Int(blurAmount *40)
boxSize = boxSize - (boxSize %2) +1
letimg =self.cgImage
varinBuffer =vImage_Buffer()
varoutBuffer =vImage_Buffer()
letinProvider =img!.dataProvider
letinBitmapData =inProvider!.data
inBuffer.width=vImagePixelCount(img!.width)
inBuffer.height=vImagePixelCount(img!.height)
inBuffer.rowBytes= img!.bytesPerRow
inBuffer.data=UnsafeMutableRawPointer(mutating:CFDataGetBytePtr(inBitmapData))
//手动申请内存
letpixelBuffer =malloc(img!.bytesPerRow* img!.height)
outBuffer.width=vImagePixelCount(img!.width)
outBuffer.height=vImagePixelCount(img!.height)
outBuffer.rowBytes= img!.bytesPerRow
outBuffer.data= pixelBuffer
varerror =vImageBoxConvolve_ARGB8888(&inBuffer,
&outBuffer,nil,vImagePixelCount(0),vImagePixelCount(0),
UInt32(boxSize),UInt32(boxSize),nil,vImage_Flags(kvImageEdgeExtend))
if(kvImageNoError!= error)
{
error =vImageBoxConvolve_ARGB8888(&inBuffer,
&outBuffer,nil,vImagePixelCount(0),vImagePixelCount(0),
UInt32(boxSize),UInt32(boxSize),nil,vImage_Flags(kvImageEdgeExtend))
if(kvImageNoError!= error)
{
error =vImageBoxConvolve_ARGB8888(&inBuffer,
&outBuffer,nil,vImagePixelCount(0),vImagePixelCount(0),
UInt32(boxSize),UInt32(boxSize),nil,vImage_Flags(kvImageEdgeExtend))
}
}
letcolorSpace =CGColorSpaceCreateDeviceRGB()
letctx =CGContext(data: outBuffer.data,
width:Int(outBuffer.width),
height:Int(outBuffer.height),
bitsPerComponent:8,
bytesPerRow: outBuffer.rowBytes,
space: colorSpace,
bitmapInfo:CGImageAlphaInfo.premultipliedLast.rawValue)
letimageRef = ctx!.makeImage()
//手动申请内存
free(pixelBuffer)
returnUIImage(cgImage: imageRef!)
}
}