做 App 時經常會用到模糊或毛玻璃效果。好消息是,iOS 已經提供了相應的 API,讓我們能方便地實現。自 iOS 7.0 之後,系統界面大量採用毛玻璃效果来提升美感,比如下圖的通知中心。

不過 iOS 7.0 的 SDK 並沒有直接開放毛玻璃 API,因此早期大家都是借助別人封裝的框架來實現。其實在此之前,系統裡就有一個類能做到——UIToolbar,而且用起來相當簡單。
創建一個 UIToolbar 實例,設置 frame 或添加約束,然後透過 barStyle 屬性選擇毛玻璃樣式,最後添加到需要效果的 view 上即可:
/* 毛玻璃樣式枚舉 UIBarStyleDefault UIBarStyleBlack UIBarStyleBlackTranslucent (推薦,配合 translucent 使用) */ UIImageView *bgImgView = [[UIImageView alloc] initWithFrame:self.view.bounds]; bgImgView.image = [UIImage imageNamed:@"huoying.jpg"]; [self.view addSubview:bgImgView]; UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, bgImgView.frame.size.width * 0.6, bgImgView.frame.size.height)]; toolbar.barStyle = UIBarStyleBlackTranslucent; [bgImgView addSubview:toolbar];

從視圖結構可以看到,UIToolbar 內部包含背景圖片、背景 view 和背景特效 view,正是這幾層疊加實現了毛玻璃:

iOS 8.0 之後蘋果新增了 UIVisualEffectView,效率極高、用法簡單。它是抽象類,需透過其子類使用;其中 UIBlurEffect 提供便捷方法快速創建毛玻璃效果,參數是樣式枚舉:
UIImageView *bgImgView = [[UIImageView alloc] initWithFrame:self.view.bounds]; bgImgView.image = [UIImage imageNamed:@"huoying.jpg"]; bgImgView.contentMode = UIViewContentModeScaleAspectFill; bgImgView.userInteractionEnabled = YES; [self.view addSubview:bgImgView]; /* 毛玻璃樣式枚舉 UIBlurEffectStyleExtraLight UIBlurEffectStyleLight UIBlurEffectStyleDark */ UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark]; UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:effect]; effectView.frame = CGRectMake(0, 0, bgImgView.frame.size.width * 0.6, bgImgView.frame.size.height); [bgImgView addSubview:effectView];
注意:這個類僅適用 iOS 8.0 之後,若項目還需兼容 iOS 7.0,就得用第一種方案。從視圖結構看,它與 Toolbar 不同——構造方法幫我們創建了一個做過毛玻璃處理的 view,再覆蓋到背景圖之上:

最後介紹一個國外大神封裝的 UIImageView 分類,使用起來只要一句代碼:
UIImageView *bgImgView = [[UIImageView alloc] initWithFrame:self.view.bounds]; bgImgView.contentMode = UIViewContentModeScaleAspectFill; // 對背景圖片進行毛玻璃處理,blurRadius 可指定,最後的 block 回調可為 nil [bgImgView setImageToBlur:[UIImage imageNamed:@"huoying.jpg"] blurRadius:10 completionBlock:nil]; bgImgView.userInteractionEnabled = YES; [self.view addSubview:bgImgView];

從視圖結構可以看出,它是直接對背景圖片做了高斯模糊處理:

總之,iOS 裡做毛玻璃就這幾種方式,按需求選用即可。demo 與大神的分類源碼可到筆者的 GitHub 上 clone。
第一種,使用 Core Image:
- (UIImage *)blurryImage:(UIImage *)image withBlurLevel:(CGFloat)blur {
CIImage *inputImage = [CIImage imageWithCGImage:image.CGImage];
CIFilter *filter = [CIFilter filterWithName:@"CIGaussianBlur" keysAndValues:kCIInputImageKey, inputImage, @"inputRadius", @(blur), nil];
CIImage *outputImage = filter.outputImage;
CGImageRef outImage = [self.context createCGImage:outputImage fromRect:[outputImage extent]];
return [UIImage imageWithCGImage:outImage];
}
第二種,使用 vImage API:
- (UIImage *)blurryImage:(UIImage *)image withBlurLevel:(CGFloat)blur {
if (blur < 0.f || blur > 1.f) {
blur = 0.5f;
}
int boxSize = (int)(blur * 100);
boxSize = boxSize - (boxSize % 2) + 1;
CGImageRef img = image.CGImage;
vImage_Buffer inBuffer, outBuffer;
vImage_Error error;
void *pixelBuffer;
CGDataProviderRef inProvider = CGImageGetDataProvider(img);
CFDataRef inBitmapData = CGDataProviderCopyData(inProvider);
inBuffer.width = CGImageGetWidth(img);
inBuffer.height = CGImageGetHeight(img);
inBuffer.rowBytes = CGImageGetBytesPerRow(img);
inBuffer.data = (void*)CFDataGetBytePtr(inBitmapData);
pixelBuffer = malloc(CGImageGetBytesPerRow(img) * CGImageGetHeight(img));
if (pixelBuffer == NULL) NSLog(@"No pixelbuffer");
outBuffer.data = pixelBuffer;
outBuffer.width = CGImageGetWidth(img);
outBuffer.height = CGImageGetHeight(img);
outBuffer.rowBytes = CGImageGetBytesPerRow(img);
error = vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, NULL, 0, 0, boxSize, boxSize, NULL, kvImageEdgeExtend);
if (error) {
NSLog(@"error from convolution %ld", error);
}
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef ctx = CGBitmapContextCreate(outBuffer.data, outBuffer.width, outBuffer.height, 8, outBuffer.rowBytes, colorSpace, kCGImageAlphaNoneSkipLast);
CGImageRef imageRef = CGBitmapContextCreateImage(ctx);
UIImage *returnImage = [UIImage imageWithCGImage:imageRef];
// 清理
CGContextRelease(ctx);
CGColorSpaceRelease(colorSpace);
free(pixelBuffer);
CFRelease(inBitmapData);
CGImageRelease(imageRef);
return returnImage;
}
第三種是網上找到的毛玻璃效果封裝,支持半徑、色調、飽和度與遮罩:
- (UIImage *)imageBluredWithRadius:(CGFloat)blurRadius tintColor:(UIColor *)tintColor saturationDeltaFactor:(CGFloat)saturationDeltaFactor maskImage:(UIImage *)maskImage {
CGRect imageRect = { CGPointZero, self.size };
UIImage *effectImage = self;
BOOL hasBlur = blurRadius > __FLT_EPSILON__;
BOOL hasSaturationChange = fabs(saturationDeltaFactor - 1.) > __FLT_EPSILON__;
if (hasBlur || hasSaturationChange) {
UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]);
CGContextRef effectInContext = UIGraphicsGetCurrentContext();
CGContextScaleCTM(effectInContext, 1.0, -1.0);
CGContextTranslateCTM(effectInContext, 0, -self.size.height);
CGContextDrawImage(effectInContext, imageRect, self.CGImage);
vImage_Buffer effectInBuffer;
effectInBuffer.data = CGBitmapContextGetData(effectInContext);
effectInBuffer.width = CGBitmapContextGetWidth(effectInContext);
effectInBuffer.height = CGBitmapContextGetHeight(effectInContext);
effectInBuffer.rowBytes = CGBitmapContextGetBytesPerRow(effectInContext);
UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]);
CGContextRef effectOutContext = UIGraphicsGetCurrentContext();
vImage_Buffer effectOutBuffer;
effectOutBuffer.data = CGBitmapContextGetData(effectOutContext);
effectOutBuffer.width = CGBitmapContextGetWidth(effectOutContext);
effectOutBuffer.height = CGBitmapContextGetHeight(effectOutContext);
effectOutBuffer.rowBytes = CGBitmapContextGetBytesPerRow(effectOutContext);
if (hasBlur) {
CGFloat inputRadius = blurRadius * [[UIScreen mainScreen] scale];
NSUInteger radius = floor(inputRadius * 3. * sqrt(2 * M_PI) / 4 + 0.5);
if (radius % 2 != 1) {
radius += 1; // 強制為奇數,才能用三次盒式模糊
}
vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, NULL, 0, 0, (short)radius, (short)radius, 0, kvImageEdgeExtend);
vImageBoxConvolve_ARGB8888(&effectOutBuffer, &effectInBuffer, NULL, 0, 0, (short)radius, (short)radius, 0, kvImageEdgeExtend);
vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, NULL, 0, 0, (short)radius, (short)radius, 0, kvImageEdgeExtend);
}
BOOL effectImageBuffersAreSwapped = NO;
if (hasSaturationChange) {
CGFloat s = saturationDeltaFactor;
CGFloat floatingPointSaturationMatrix[] = {
0.0722 + 0.9278 * s, 0.0722 - 0.0722 * s, 0.0722 - 0.0722 * s, 0,
0.7152 - 0.7152 * s, 0.7152 + 0.2848 * s, 0.7152 - 0.7152 * s, 0,
0.2126 - 0.2126 * s, 0.2126 - 0.2126 * s, 0.2126 + 0.7873 * s, 0,
0, 0, 0, 1,
};
const int32_t divisor = 256;
NSUInteger matrixSize = sizeof(floatingPointSaturationMatrix) / sizeof(floatingPointSaturationMatrix[0]);
int16_t saturationMatrix[matrixSize];
for (NSUInteger i = 0; i < matrixSize; ++i) {
saturationMatrix[i] = (int16_t)roundf(floatingPointSaturationMatrix[i] * divisor);
}
if (hasBlur) {
vImageMatrixMultiply_ARGB8888(&effectOutBuffer, &effectInBuffer, saturationMatrix, divisor, NULL, NULL, kvImageNoFlags);
effectImageBuffersAreSwapped = YES;
} else {
vImageMatrixMultiply_ARGB8888(&effectInBuffer, &effectOutBuffer, saturationMatrix, divisor, NULL, NULL, kvImageNoFlags);
}
}
if (!effectImageBuffersAreSwapped)
effectImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
if (effectImageBuffersAreSwapped)
effectImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
// 開啟上下文輸出圖像
UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]);
CGContextRef outputContext = UIGraphicsGetCurrentContext();
CGContextScaleCTM(outputContext, 1.0, -1.0);
CGContextTranslateCTM(outputContext, 0, -self.size.height);
// 畫底圖
CGContextDrawImage(outputContext, imageRect, self.CGImage);
// 畫模糊效果
if (hasBlur) {
CGContextSaveGState(outputContext);
if (maskImage) {
CGContextClipToMask(outputContext, imageRect, maskImage.CGImage);
}
CGContextDrawImage(outputContext, imageRect, effectImage.CGImage);
CGContextRestoreGState(outputContext);
}
// 添加色調渲染
if (tintColor) {
CGContextSaveGState(outputContext);
CGContextSetFillColorWithColor(outputContext, tintColor.CGColor);
CGContextFillRect(outputContext, imageRect);
CGContextRestoreGState(outputContext);
}
UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return outputImage;
}