kondratyevdev kondratyevdev - 5 months ago 40
iOS Question

Creating a blurring overlay view

In the Music app of the new iOS, we can see an album cover behind a view that blurs it.

How can something like that be accomplished? I've read the documentation, but did not find anything there.


Answer

For iOS 8+, you can use UIVisualEffectView to achieve this effect. This is a native API that has been fine tuned for performance and great battery life, and it's easy to implement.

Swift:

//only apply the blur if the user hasn't disabled transparency effects
if !UIAccessibilityIsReduceTransparencyEnabled() {
    self.view.backgroundColor = UIColor.clearColor()

    let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark)
    let blurEffectView = UIVisualEffectView(effect: blurEffect)
    //always fill the view
    blurEffectView.frame = self.view.bounds
    blurEffectView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]

    self.view.addSubview(blurEffectView) //if you have more UIViews, use an insertSubview API to place it where needed
} 
else {
    self.view.backgroundColor = UIColor.blackColor()
}

Objective-C:

if (!UIAccessibilityIsReduceTransparencyEnabled()) {
    self.view.backgroundColor = [UIColor clearColor];

    UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
    UIVisualEffectView *blurEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
    blurEffectView.frame = self.view.bounds;
    blurEffectView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

    [self.view addSubview:blurEffectView];
}  
else {
    self.view.backgroundColor = [UIColor blackColor];
}
Comments