毛玻璃效果能為介面增添現代感與層次。本文示範如何封裝一個 UIImage 分類,透過 Accelerate 框架的 vImage 函式實作可調參數的模糊、飽和度與著色渲染,並結合影圖流與截圖,做出點擊放大時的毛玻璃蒙版過場動畫。
先看最終效果:



關鍵程式碼如下:


// UIImage+BlurGlass.h #import <UIKit/UIKit.h> @interface UIImage (BlurGlass) /* 參數說明: alpha:透明度 0~1,0為白,1為深灰色 radius:半徑,默認30,推薦值3,半徑越大越模糊 colorSaturationFactor:色彩飽和度因子,0為黑白灰,9為濃彩色,1為原色,默認1.8 */ - (UIImage *)imgWithLightAlpha:(CGFloat)alpha radius:(CGFloat)radius colorSaturationFactor:(CGFloat)colorSaturationFactor; // 封裝好、供外界調用的方法 - (UIImage *)imgWithBlur; @end
// UIImage+BlurGlass.m
#import "UIImage+BlurGlass.h"
#import <Accelerate/Accelerate.h>
@implementation UIImage (BlurGlass)
- (UIImage *)imgWithLightAlpha:(CGFloat)alpha radius:(CGFloat)radius colorSaturationFactor:(CGFloat)colorSaturationFactor {
UIColor *tintColor = [UIColor colorWithWhite:1.0 alpha:alpha];
return [self imgBluredWithRadius:radius tintColor:tintColor saturationDeltaFactor:colorSaturationFactor maskImage:nil];
}
- (UIImage *)imgWithBlur {
return [self imgWithLightAlpha:0.1 radius:3 colorSaturationFactor:1];
}
// 內部核心方法,封裝毛玻璃效果
- (UIImage *)imgBluredWithRadius:(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; // force radius to be odd so that the three box-blur methodology works.
}
vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, NULL, 0, 0, radius, radius, 0, kvImageEdgeExtend);
vImageBoxConvolve_ARGB8888(&effectOutBuffer, &effectInBuffer, NULL, 0, 0, radius, radius, 0, kvImageEdgeExtend);
vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, NULL, 0, 0, radius, 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;
}
@end
以下控制器展示了如何將毛玻璃分類應用於截圖蒙版,並搭配 CollectionView 與放大動畫。
// MineController.m #import "MineController.h" #import "ImgDownloadTool.h" #import "UIImage+BoxBlur.h" #import "GirlCell.h" #define kItemW 240 #define kItemH 320 @interface MineController (){ NSMutableArray *_imgArr; UIWebView *_webView; UIImageView *_coverBlurImgView; // 毛玻璃蒙版 UIImageView *_showingImgView; // 點擊後弹出的大圖 } @end @implementation MineController - (void)viewDidLoad { [super viewDidLoad]; self.title = @"我的青春誰做主"; NSBundle *mainBundle = [NSBundle mainBundle]; NSString *fullPath = [mainBundle pathForResource:@"sinaImgArr.plist" ofType:nil]; _imgArr = [NSArray arrayWithContentsOfFile:fullPath]; [self addCollectionView]; [self.collectionView registerNib:[UINib nibWithNibName:@"GirlCell" bundle:nil] forCellWithReuseIdentifier:@"GirlCell"]; self.collectionView.alwaysBounceVertical = YES; self.collectionView.backgroundColor = kGlobalBg; _coverBlurImgView = [[UIImageView alloc] init]; [self.view addSubview:_coverBlurImgView]; _showingImgView = [[UIImageView alloc] init]; _showingImgView.backgroundColor = [UIColor clearColor]; [self.view addSubview:_showingImgView]; _showingImgView.contentMode = UIViewContentModeScaleAspectFit; _showingImgView.userInteractionEnabled = YES; [_showingImgView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showingImgTap)]]; } - (void)addCollectionView { UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init]; layout.itemSize = CGSizeMake(kItemW, kItemH); layout.minimumLineSpacing = 20; self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout]; self.collectionView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth; self.collectionView.delegate = self; self.collectionView.dataSource = self; [self.view addSubview:self.collectionView]; } // 點擊cell時:截屏、加上毛玻璃、放大顯示大圖 - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath { [self screenShot]; _coverBlurImgView.alpha = 1; _coverBlurImgView.hidden = NO; // 調用分類方法進行毛玻璃處理 _coverBlurImgView.image = [_coverBlurImgView.image imgWithBlur]; _showingImgView.hidden = NO; CGRect temp = _showingImgView.frame; CGFloat x = self.view.frame.size.width * 0.5; CGFloat y = self.view.frame.size.height * 0.5; temp = CGRectMake(x, y, 0, 0); _showingImgView.frame = temp; _showingImgView.alpha = 0; [UIView animateWithDuration:0.5 animations:^{ [ImgDownloadTool imgDownloadWithUrl:_imgArr[indexPath.row] tmpImgName:kImgPlaceHolder imageView:_showingImgView]; _showingImgView.alpha = 1; _showingImgView.frame = self.view.bounds; }]; } // 使用上下文截圖 - (void)screenShot { CGSize size = self.view.frame.size; UIGraphicsBeginImageContextWithOptions(size, YES, 0.0); CGRect rect = CGRectMake(0, 0, size.width, size.height); [self.view drawViewHierarchyInRect:rect afterScreenUpdates:NO]; UIImage *snapshot = UIGraphicsGetImageFromCurrentImageContext(); _coverBlurImgView.image = snapshot; UIGraphicsEndImageContext(); } - (void)showingImgTap { [UIView animateWithDuration:0.5 animations:^{ CGRect temp = _showingImgView.frame; CGFloat x = self.view.frame.size.width * 0.5; CGFloat y = self.view.frame.size.height * 0.5; temp = CGRectMake(x, y, 0, 0); _showingImgView.frame = temp; _showingImgView.alpha = 0; } completion:^(BOOL finished) { _showingImgView.hidden = YES; _coverBlurImgView.hidden = YES; }]; } - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; } @end
透過 UIImage 的分類封裝,模糊、飽和度調整與著色渲染等複雜運算被完全隱藏,外部只需一行 [image imgWithBlur] 即可套用,非常適合需要高質感視覺效果的場景。