You can make an extension of UIImageView.
Swift 2.0
import Foundation
import UIKit
extension UIImageView
{
func makeBlurImage(targetImageView:UIImageView?)
{
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = targetImageView!.bounds
blurEffectView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] // for supporting device rotation
targetImageView?.addSubview(blurEffectView)
}
}
Usage:
override func viewDidLoad()
{
super.viewDidLoad()
let sampleImageView = UIImageView(frame: CGRectMake(0, 200, 300, 325))
let sampleImage:UIImage = UIImage(named: "ic_120x120")!
sampleImageView.image = sampleImage
//Convert To Blur Image Here
sampleImageView.makeBlurImage(sampleImageView)
self.view.addSubview(sampleImageView)
}
Swift 3 Extension
import Foundation
import UIKit
extension UIImageView
{
func addBlurEffect()
{
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.light)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = self.bounds
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] // for supporting device rotation
self.addSubview(blurEffectView)
}
}
Usage:
yourImageView.addBlurEffect()
Addendum:
extension UIView {
/// Remove UIBlurEffect from UIView
func removeBlurEffect() {
let blurredEffectViews = self.subviews.filter{$0 is UIVisualEffectView}
blurredEffectViews.forEach{ blurView in
blurView.removeFromSuperview()
}
}
Swift 5.0:
import UIKit
extension UIImageView {
func applyBlurEffect() {
let blurEffect = UIBlurEffect(style: .light)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = bounds
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
addSubview(blurEffectView)
}
}