Quantcast
Channel: Kodeco | High quality programming tutorials: iOS, Android, Swift, Kotlin, Unity, and more
Viewing all articles
Browse latest Browse all 4396

UIVisualEffectView Tutorial: Getting Started

$
0
0
Update note: This tutorial has been updated to iOS 11 and Swift 4 by Evan Dekhayser. The original tutorial was written by Ryan Nystrom.

UIVisualEffectView Tutorial: Getting Started

Ever since the design of iOS dramatically changed in iOS 7, blurs have played an important part in app design. When used appropriately, blurs can significantly improve the usability and appearance of your apps.

Let’s take a look at how Apple uses blurs at a system level. One of the most notable examples is in Control Center. The blurred background preserves the context of the action – Control Center is not its own app, but a panel shown above the active app.

Notification Center uses this effect as well, but rather than blurring the entire background, each Notification Center extension or notification has its own blurred background. Besides simply looking beautiful, this blur helps each element stand out just the right amount.

UIVisualEffectView tutorial

So how do you recreate these types of blurs in your own apps? Use the built-in UIVisualEffectView! In this UIVisualEffectView tutorial, you are going to learn everything you need to know to make your apps stand out using blurs.

Clear Facts on Blurs

Executing blurs in a tasteful – and efficient – manner takes a bit of finesse. In this section, you’ll learn about a common algorithm used to create a blurring effect.

How Blurs Work

All blurs start with an image. To achieve a blur, you apply a blurring algorithm to each pixel in the image; the resulting image then contains an evenly blurred version of the original image. Blurring algorithms vary in style and complexity, but in this section we’ll examine a common algorithm known as Gaussian blur.

Blurring algorithms generally examine each pixel of an image and use the surrounding pixels to calculate new color values for that pixel. For example, consider the following theoretical image grid:

blur-how1

Each cell in the above grid represents an individual pixel, and each pixel has a value between 1 and 10. Consider the case where the algorithm is evaluating the center pixel. The algorithm averages the values of the surrounding pixels and inserts this averaged value into the center pixel, resulting in the following new pixel grid:

blur-how2

You then repeat this process for every pixel in the original image.
The sample algorithm above only examined one pixel in each direction to create the new averaged value. You can expand this blur radius even further to increase the amount of blurring in your image, as demonstrated in the image below:

3px and 16px Gaussian Blur applied to an image

3px and 16px Gaussian Blur applied to an image

Note: Generally, the greater the blur radius, the greater the processing power required to process the image. iOS offloads most image processing activities to the GPU to keep the main thread free.

Blur Design Strategies

Humans have a tendency to pay attention to elements that are in-focus and ignore those that aren’t. Believe it or not, this is a natural consequence of how our eyes work. Focusing on an object as it moves closer or further away from the eye is known as accommodation; it’s what helps you perceive the depth and distance of objects around you.

App designers exploit this fact and blur unimportant items on the screen to direct the user’s attention to the remaining non-blurred elements, as demonstrated in this screenshot of the popular Twitter client Tweetbot:

The user interface in the background is barely recognizable in the image above. This provides contextual awareness to the user about where they are in the navigational hierarchy. For instance, you’d expect to return to the blurred-out view in the background once you select one of the accounts displayed.

Note: Be careful about the overuse of blurs in your mobile apps. Although blurs can provide great-looking effects, they can be distracting and annoying if used inappropriately or too often.

Follow the standard design approach to use blurs to direct a user’s attention to things that matter and you’ll seldom go wrong. See the Designing for iOS section of the iOS Human Interface Guidelines document found on Apple’s iOS developer center for more on this subject.

Getting Started

To learn how to implement blurring, you’ll add some blur effects to a brand new Brothers Grimm fairytale app – aptly named Grimm.

The app displays a library of fairytales to the user. When the user taps on a fairytale, the app presents the full story on screen. The user can customize the display font, text alignment, or even the color theme for daytime or nighttime reading.

Start by downloading the starter project, then open Grimm.xcodeproj in Xcode. Open Main.storyboard and take a look at the view controllers contained in the app as illustrated below:

You can ignore the very first view controller in the image above as it’s simply the root navigation controller of the app. Taking each numbered view controller in turn, you’ll see the following:

  1. The first view controller is StoryListController, which displays a list of all of the fairy tales in the database.
  2. Tapping a story in the list segues the user to StoryViewController, which displays the title and text of the selected fairy tale.
  3. OptionsController is contained within StoryViewController and displays the available font, text alignment, and color options. To display it, simply tap the top-right ellipses icon in the detail controller.

Build and run. You’ll see the initial screen as shown below:

Have some fun exploring the app; select different stories, tap the ellipsis icon and swipe to different fonts and reading modes to understand how the user interface functions.

Once you have a handle on how the app behaves, head straight to the next section to learn how to apply blur effects to the app.

Blur Effects using UIVisualEffectView

UIKit provides an entire suite of visual effects goodies. UIBlurEffect, a subclass of UIVisualEffect, is particularly relevant to your interests. UIBlurEffect provides the nice blurs you see in navigation bars, Notification Center, and Control Center – and you can use it in your apps as well.

Adding a UIBlurEffect

In this project, you will use blur to make the OptionsController stand out on top of the story. Let’s jump right in!

Open OptionsController.swift and add the following code to the end of viewDidLoad:

// 1
view.backgroundColor = .clear
// 2
let blurEffect = UIBlurEffect(style: .light)
// 3
let blurView = UIVisualEffectView(effect: blurEffect)
// 4
blurView.translatesAutoresizingMaskIntoConstraints = false
view.insertSubview(blurView, at: 0)

Taking each numbered comment in turn:

  1. In order for the UIVisualEffectView to actually blur the content, its superview must be transparent. To do this, you change the background color to be clear.
  2. Create a UIBlurEffect with a UIBlurEffectStyle.light style. This defines what style of blur is used. The other available styles are .extraLight and .dark, .extraDark, regular, and prominent.
  3. Create a UIVisualEffectView with the blur you just created. This class is a subclass of UIView; its sole purpose is to define and display complex visual effects.
  4. Disable translating the auto-resizing masks into constraints on the blurView — you’ll manually add constraints in just a moment — and add it at the bottom of the view stack. If you just added blurView on top of the view, it would end up blurring all of the controls underneath it instead!

Now you need to ensure your blurView is laid out properly with the rest of the view.

Add the following code to the end of viewDidLoad:

NSLayoutConstraint.activate([
  blurView.heightAnchor.constraint(equalTo: view.heightAnchor),
  blurView.widthAnchor.constraint(equalTo: view.widthAnchor),
  ])

These constraints keep the frame of the blurView consistent with that of the OptionsController view.

Build and run. Select a fairy tale, tap the ellipsis button, and then scroll the text. Behold as the blur updates in real-time.

OptionsController with applied UIVisualEffectView

You now have a dynamic blur effect in your app that was not only easy to implement but looks great too.

Adding Vibrancy to your Blur

Blur effects are great – but as usual, Apple has taken it to the next level with UIVibrancyEffect, which when used in combination with UIVisualEffectView adjusts the colors of the content to make it feel more vivid.

The following image demonstrates how vibrancy makes your labels and icons pop off the screen, while at the same time blending with the background itself:

vibrancy

The left side of the image shows a normal label and button, while the right side shows a label and button with vibrancy applied.

Note: UIVibrancyEffect must be added to the contentView of a UIVisualEffectView that has been set up and configured with a UIBlurEffect object; otherwise, there won’t be any blurs to apply a vibrancy effect to!

Open OptionsController.swift and add the following code to the end of viewDidLoad:

// 1
let vibrancyEffect = UIVibrancyEffect(blurEffect: blurEffect)
// 2
let vibrancyView = UIVisualEffectView(effect: vibrancyEffect)
vibrancyView.translatesAutoresizingMaskIntoConstraints = false
// 3
vibrancyView.contentView.addSubview(optionsView)
// 4
blurView.contentView.addSubview(vibrancyView)

Taking each numbered comment in turn:

  1. Create a UIVibrancyEffect that uses the blurEffect you set up earlier. UIVibrancyEffect is another subclass of UIVisualEffect.
  2. Create a UIVisualEffectView to contain the vibrancy effect. This process is exactly the same as creating a blur. Since you’re using Auto Layout, you make sure to disable auto-resizing translations here.
  3. Add optionsView as a subview of your vibrancy view’s contentView; this ensures the vibrancy effect will be applied to the view that contains all of the controls.
  4. Finally you add the vibrancy view to the blur view’s contentView to complete the effect.

Next, you need to set up the Auto Layout constraints for the vibrancy view so that it has the same dimensions as the blur view, and for the options view to be centered in the vibrancy view.

Add the following constraints at the end of viewDidLoad:

NSLayoutConstraint.activate([
  vibrancyView.heightAnchor.constraint(equalTo: blurView.contentView.heightAnchor),
  vibrancyView.widthAnchor.constraint(equalTo: blurView.contentView.widthAnchor),
  vibrancyView.centerXAnchor.constraint(equalTo: blurView.contentView.centerXAnchor),
  vibrancyView.centerYAnchor.constraint(equalTo: blurView.contentView.centerYAnchor)
  ])

NSLayoutConstraint.activate([
  optionsView.centerXAnchor.constraint(equalTo: vibrancyView.contentView.centerXAnchor),
  optionsView.centerYAnchor.constraint(equalTo: vibrancyView.contentView.centerYAnchor),
  ])

There’s one thing you have left to do before this will work. If you look at the beginning of viewDidLoad, you already added optionsView as a subview – and views can only have a single superview.

At the beginning of viewDidLoad, comment out the following code:

view.addSubview(optionsView)

NSLayoutConstraint.activate([
  view.centerXAnchor.constraint(equalTo: optionsView.centerXAnchor),
  view.centerYAnchor.constraint(equalTo: optionsView.centerYAnchor)
  ])

Build and run. Bring up the options view to see your new vibrancy effect in action:

Light-styled UIVisualEffectView with Vibrancy on

Unless you have high-contrast vision, the vibrancy effect makes it really difficult to read the labels and controls. What’s going on?

Ah – the content behind the blur view is light and you’re applying a UIBlurEffectStyle.light effect. That’s counterproductive, to be sure.

Modify the line near the top of viewDidLoad that initializes the blurEffect:

let blurEffect = UIBlurEffect(style: .dark)

This changes the blur effect to add more contrast between the background and text.

Build and run. You’re now experiencing some true vibrancy:

Dark-styled UIVisualEffectView with Vibrancy on

Accessibility

When it comes to blurs, there is one last thing you need to consider: what if the user has blurs disabled?

In the simulator or on your device, open the Settings app and go to General\Accessibility\Increase Contrast, and enable Reduce Transparency. Go back to the app, and open the options view once again.

Well, that isn’t going to work at all! In this situation, going back to what you started out with is a better alternative.

Luckily, you can check if this accessibility setting is enabled using UIAccessibilityIsReduceTransparencyEnabled(). If you know that this setting is enabled, you can change the way your app looks and behaves.

Using the code you commented out before, add the following right before you set the view’s background color in viewDidLoad:

guard UIAccessibilityIsReduceTransparencyEnabled() == false else {
  view.addSubview(optionsView)

  NSLayoutConstraint.activate([
    view.centerXAnchor.constraint(equalTo: optionsView.centerXAnchor),
    view.centerYAnchor.constraint(equalTo: optionsView.centerYAnchor)
    ])

  return
}

This code checks to see if Reduce Transparency is enabled. If it is, you ignore all the code you just wrote and go back to the original layout without any blurring.

Build and run the app, and you’ll see that the options menu looks normal once again.

Where to Go From Here?

You can download the finished project here.

You’ve seen how images can be blurred, as well as how to create real-time blur effects using UIVisualEffectView. You can just as easily add advanced blur effects to your own app! There’s many more effects and options you could dive in to, and the best place to continue your exploration would be in Apple’s official UIVisualEffectView documentation.

UIVisualEffectViews update in real-time, so you can achieve all sorts of weird and wonderful things with these effects. While you might be tempted to go ahead and blur all the things, keep in mind what was discussed earlier in the tutorial regarding using these effects sparingly and only where appropriate. As is often the case, with blur and vibrancy, less is definitely more.

If you have any questions or comments about this UIVisualEffectView tutorial or visual effects in general, please join the forum discussion below!

The post UIVisualEffectView Tutorial: Getting Started appeared first on Ray Wenderlich.


Viewing all articles
Browse latest Browse all 4396

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>