Friday, 26 Apr 2024
blog

Creating a blurring overlay view

I think the easiest solution to this is to override UIToolbar, which blurs everything behind it in iOS 7. It’s quite sneaky, but it’s very simple for you to implement, and fast!

You can do it with any view, just make it a subclass of UIToolbar instead of UIView. You can even do it with a UIViewController‘s view property, for example…

1) create a new class that is a “Subclass of” UIViewController and check the box for “With XIB for user interface”.

2) Select the View and go to the identity inspector in the right-hand panel (alt-command-3). Change the “Class” to UIToolbar. Now go to the attributes inspector (alt-command-4) and change the “Background” color to “Clear Color”.

3) Add a subview to the main view and hook it up to an IBOutlet in your interface. Call it backgroundColorView. It will look something like this, as a private category in the implementation (.m) file.

@interface BlurExampleViewController ()
@property (weak, nonatomic) IBOutlet UIView *backgroundColorView;
@end

4) Go to the view controller implementation (.m) file and change the -viewDidLoad method, to look as follows:

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.barStyle = UIBarStyleBlack; // this will give a black blur as in the original post
    self.backgroundColorView.opaque = NO;
    self.backgroundColorView.alpha = 0.5;
    self.backgroundColorView.backgroundColor = [UIColor colorWithWhite:0.3 alpha:1];
}

This will give you a dark gray view, which blurs everything behind it. No funny business, no slow core image blurring, using everything that is at your fingertips provided by the OS/SDK.

You can add this view controller’s view to another view, as follows:

[self addChildViewController:self.blurViewController];
[self.view addSubview:self.blurViewController.view];
[self.blurViewController didMoveToParentViewController:self];

// animate the self.blurViewController into view

Let me know if anything is unclear, I’ll be happy to help!

Edit

UIToolbar has been changed in 7.0.3 to give possibly-undesirable effect when using a coloured blur.

We used to be able to set the colour using barTintColor, but if you were doing this before, you will need to set the alpha component to less than 1. Otherwise your UIToolbar will be completely opaque colour – with no blur.

This can be achieved as follows: (bearing in mind self is a subclass of UIToolbar)

UIColor *color = [UIColor blueColor]; // for example
self.barTintColor = [color colorWithAlphaComponent:0.5];

This will give a blue-ish tint to the blurred view.

Post Comment