從 iOS 8 開始,想要做出毛玻璃(模糊)效果變得非常簡單——只要在需要模糊的 UIView 上,疊加一層 UIVisualEffectView 物件即可,系統會自動完成背後的模糊運算。
效果如下圖:

UIImageView *imageview = [[UIImageView alloc] init]; imageview.frame = CGRectMake(10, 100, 300, 300); imageview.image = [UIImage imageNamed:@"2"]; imageview.contentMode = UIViewContentModeScaleAspectFit; imageview.userInteractionEnabled = YES; [self.view addSubview:imageview]; // 建立模糊效果並指定風格 UIBlurEffect *blur = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]; UIVisualEffectView *effectview = [[UIVisualEffectView alloc] initWithEffect:blur]; effectview.frame = CGRectMake(0, 0, imageview.size.width / 2, 300); // 加到欲模糊的視圖上 [imageview addSubview:effectview]; // 效果視圖的 contentView 才是用來承放前景內容的地方 UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem]; btn.frame = CGRectMake(10, 50, 100, 40); [btn setTitle:@"btn" forState:UIControlStateNormal]; [effectview.contentView addSubview:btn];
UIBlurEffect 提供三種風格:Light、Dark 與 ExtraLight,可依背景明暗挑選,讓前景文字維持足夠對比。
最容易被忽略的一點是:任何要顯示在模糊層「之上」的元件,都必須加到 effectview.contentView,而不是直接加在 effectview 上面。若加錯位置,元件可能不會正常顯示或被模糊處理。
另外,effectview.userInteractionEnabled 預設為 YES,會攔截觸控事件。如果這層只是純裝飾、不該阻擋下方操作,記得把它設為 NO,或把 contentView 的互動關掉。
這個 API 在 iOS 8 以前無法使用;若專案仍需支援舊版本,就得回頭使用第三方模糊庫或手寫 Core Image 的 gaussian blur 才行。