1 /** 2 * 模糊背景 3 * 4 * @param image 需要模糊的图片 5 * @param blur 高斯模糊的值 6 * 7 * @return 8 */ 9 - (UIImage *)blurryImage:(UIImage *)image withBlurLevel:(CGFloat)blur 10 { 11 if ((blur < 0.0f) || (blur > 1.0f)) { 12 blur = 0.5f; 13 } 14 15 int boxSize = (int)(blur * 100); 16 boxSize -= (boxSize % 2) + 1; 17 18 CGImageRef img = image.CGImage; 19 20 vImage_Buffer inBuffer, outBuffer; 21 vImage_Error error; 22 void *pixelBuffer; 23 24 CGDataProviderRef inProvider = CGImageGetDataProvider(img); 25 CFDataRef inBitmapData = CGDataProviderCopyData(inProvider); 26 27 inBuffer.width = CGImageGetWidth(img); 28 inBuffer.height = CGImageGetHeight(img); 29 inBuffer.rowBytes = CGImageGetBytesPerRow(img); 30 inBuffer.data = (void*)CFDataGetBytePtr(inBitmapData); 31 32 pixelBuffer = malloc(CGImageGetBytesPerRow(img) * CGImageGetHeight(img)); 33 34 outBuffer.data = pixelBuffer; 35 outBuffer.width = CGImageGetWidth(img); 36 outBuffer.height = CGImageGetHeight(img); 37 outBuffer.rowBytes = CGImageGetBytesPerRow(img); 38 39 error = vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, NULL, 0, 0, boxSize, boxSize, NULL, kvImageEdgeExtend); 40 41 CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 42 CGContextRef ctx = CGBitmapContextCreate(outBuffer.data, outBuffer.width, outBuffer.height, 8, outBuffer.rowBytes, colorSpace, CGImageGetBitmapInfo(image.CGImage)); 43 44 CGImageRef imageRef = CGBitmapContextCreateImage (ctx); 45 UIImage *returnImage = [UIImage imageWithCGImage:imageRef]; 46 47 //clean up 48 CGContextRelease(ctx); 49 CGColorSpaceRelease(colorSpace); 50 51 free(pixelBuffer); 52 CFRelease(inBitmapData); 53 54 CGColorSpaceRelease(colorSpace); 55 CGImageRelease(imageRef); 56 57 return returnImage; 58 }
时间: 2024-10-19 14:04:46