How to apply blur to a UIView?

This should work. I commented in the code to help you understand what’s going on:

//To take advantage of CIFilters, you have to import the Core Image framework
#import <CoreImage/CoreImage.h>

//Get a UIImage from the UIView
UIGraphicsBeginImageContext(myView.bounds.size);
[myView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

//Blur the UIImage with a CIFilter
CIImage *imageToBlur = [CIImage imageWithCGImage:viewImage.CGImage];    
CIFilter *gaussianBlurFilter = [CIFilter filterWithName: @"CIGaussianBlur"]; 
[gaussianBlurFilter setValue:imageToBlur forKey: @"inputImage"]; 
[gaussianBlurFilter setValue:[NSNumber numberWithFloat: 10] forKey: @"inputRadius"];
CIImage *resultImage = [gaussianBlurFilter valueForKey: @"outputImage"]; 
UIImage *endImage = [[UIImage alloc] initWithCIImage:resultImage];

//Place the UIImage in a UIImageView
UIImageView *newView = [[UIImageView alloc] initWithFrame:self.view.bounds];
newView.image = endImage;
[self.view addSubview:newView];

If you have any questions about the code, just leave it in the comments.

Note: CIGaussianBlur isn’t present on iOS as of 5.1, so you must find a different way to blur the view for devices 5.x+ (Thanks to @BradLarson for this tip). The accepted answer in this question looks promising as a replacement, as does this library.

Leave a Comment