做開發(fā)時肾档,總是使用系統(tǒng)默認(rèn)的白色背景會顯得有些生硬辫继,所以當(dāng)我們以展示圖片為目的時姑宽,不妨將圖片放大、再做高斯模糊處理以作為背景舵变。
我把這個處理過程用 Swift 封裝成了一個函數(shù)瘦穆,供大家參考。
//創(chuàng)建高斯模糊效果的背景
func createBlurBackground (image:UIImage,view:UIView,blurRadius:Float) {
//處理原始NSData數(shù)據(jù)
let originImage = CIImage(CGImage: image.CGImage )
//創(chuàng)建高斯模糊濾鏡
let filter = CIFilter(name: "CIGaussianBlur")
filter.setValue(originImage, forKey: kCIInputImageKey)
filter.setValue(NSNumber(float: blurRadius), forKey: "inputRadius")
//生成模糊圖片
let context = CIContext(options: nil)
let result:CIImage = filter.valueForKey(kCIOutputImageKey) as! CIImage
let blurImage = UIImage(CGImage: context.createCGImage(result, fromRect: result.extent()))
//將模糊圖片加入背景
let w = self.view.frame.width
let h = self.view.frame.height
let blurImageView = UIImageView(frame: CGRectMake(-w/2, -h/2, 2*w, 2*h)) //模糊背景是界面的4倍大小
blurImageView.contentMode = UIViewContentMode.ScaleAspectFill //使圖片充滿ImageView
blurImageView.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight //保持原圖長寬比
blurImageView.image = blurImage
self.view.insertSubview(blurImageView, belowSubview: view) //保證模糊背景在原圖片View的下層
}
三個參數(shù)分別為:image(原始清晰圖片)绵咱、view(你需要將生成的模糊背景插入在這個view的下層當(dāng)做背景)悲伶、blurRadius(高斯模糊處理的模糊半徑)
其中 let context = CIContext(options: nil)
這一句,在真機(jī)測試時钠绍,會引起控制臺報(bào)錯
這是蘋果的一個 Bug 花沉,想要回避這個信息輸出可以用下面這一句進(jìn)行替換:
let context = CIContext(options:[kCIContextUseSoftwareRenderer : true])
這句可以使圖片渲染工作在 CPU 而非 GPU 完成主穗,從而繞過這個 Bug,但是會引起效率下降忽媒,耗時大大增加晦雨,不推薦使用。
使用效果展示:
self.createBlurBackground(img, view: self.gifView, blurRadius: 50)