1.首先導入系統庫 Accelerate.framework
2.其次在要實現毛玻璃效果的頁面添加頭文件 #import
3.再次添加實現函數如下:
//加模糊效果函數,傳入參數:image是圖片,blur是模糊度(0~2.0之間)
- (UIImage *)blurryImage:(UIImage *)image withBlurLevel:(CGFloat)blur
{
//模糊度,
if ((blur < 0.1f) || (blur > 2.0f))
{
blur = 0.5f;
}
//boxSize必須大於0
int boxSize = (int)(blur * 100);
boxSize -= (boxSize % 2) + 1;
NSLog(@"boxSize:%i",boxSize);
//圖像處理
CGImageRef img = image.CGImage;
//圖像緩存,輸入緩存,輸出緩存
vImage_Buffer inBuffer, outBuffer;
vImage_Error error;
//像素緩存
void *pixelBuffer;
//數據源提供者,Defines an opaque type that supplies Quartz with data.
CGDataProviderRef inProvider = CGImageGetDataProvider(img);
// provider’s data.
CFDataRef inBitmapData = CGDataProviderCopyData(inProvider);
//寬,高,字節/行,data
inBuffer.width = CGImageGetWidth(img);
inBuffer.height = CGImageGetHeight(img);
inBuffer.rowBytes = CGImageGetBytesPerRow(img);
inBuffer.data = (void*)CFDataGetBytePtr(inBitmapData);
//像數緩存,字節行*圖片高
pixelBuffer = malloc(CGImageGetBytesPerRow(img) * CGImageGetHeight(img));
outBuffer.data = pixelBuffer;
outBuffer.width = CGImageGetWidth(img);
outBuffer.height = CGImageGetHeight(img);
outBuffer.rowBytes = CGImageGetBytesPerRow(img);
// 第三個中間的緩存區,抗鋸齒的效果
void *pixelBuffer2 = malloc(CGImageGetBytesPerRow(img) * CGImageGetHeight(img));
vImage_Buffer outBuffer2;
outBuffer2.data = pixelBuffer2;
outBuffer2.width = CGImageGetWidth(img);
outBuffer2.height = CGImageGetHeight(img);
outBuffer2.rowBytes = CGImageGetBytesPerRow(img);
//將一個隱式的M×N區域顆粒和具有箱式濾波器的效果的ARGB8888源圖像進行卷積運算得到作用區域。
error = vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer2, NULL, 0, 0, boxSize, boxSize, NULL, kvImageEdgeExtend);
error = vImageBoxConvolve_ARGB8888(&outBuffer2, &inBuffer, NULL, 0, 0, boxSize, boxSize, NULL, kvImageEdgeExtend);
error = vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, NULL, 0, 0, boxSize, boxSize, NULL, kvImageEdgeExtend);
if (error)
{
NSLog(@"error from convolution %ld", error);
}
// NSLog(@"字節組成部分:%zu",CGImageGetBitsPerComponent(img));
//顏色空間DeviceRGB
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
//用圖片創建上下文,CGImageGetBitsPerComponent(img),7,8
CGContextRef ctx = CGBitmapContextCreate(
outBuffer.data,
outBuffer.width,
outBuffer.height,
8,
outBuffer.rowBytes,
colorSpace,
CGImageGetBitmapInfo(image.CGImage));
//根據上下文,處理過的圖片,重新組件
CGImageRef imageRef = CGBitmapContextCreateImage (ctx);
UIImage *returnImage = [UIImage imageWithCGImage:imageRef];
//clean up
CGContextRelease(ctx);
CGColorSpaceRelease(colorSpace);
free(pixelBuffer);
free(pixelBuffer2);
CFRelease(inBitmapData);
CGImageRelease(imageRef);
return returnImage;
}
4.使用的時候直接傳入所需參數,將返回的image直接運行就可以了UIImage * maoImage = [UIImage imageNamed:@"aboutBackImage.jpg"];;
tabBarImage.image = [self blurryImage:maoImage withBlurLevel:0.5];
大功告成,(*^__^*) ……小伙伴們快去試試效果吧~