July 9, 2014

Adding View Effects in iOS 8

By

In iOS 8, Apple has added UIKit level support for effects such as blur and vibrancy. These effects are seen in system-level UIs such as the blur effect shown when opening a folder or swiping to the lock screen, and can now be added to your own applications with just a few lines of code.

view effects

Blur Effect

The first effect you can use is the blur effect, represented by the UIBlurEffect class. Adding a blur effect is easy. Create a UIBlurEffect and a UIVisualEffectView from the effect. Then just add the effect view to the view hierarchy.

For example, the following code adds a blur effect:

var blur = UIBlurEffect.FromStyle (UIBlurEffectStyle.Light);
var blurView = new UIVisualEffectView (blur) {
  Frame = new RectangleF (0, 0, imageView.Frame.Width, 400)
};
View.Add (blurView);

This code dynamically blurs the content beneath it. For instance, when added to a view hierarchy containing a scrollable image, the effect of the blur changes at runtime as the image is moved:

blur

The blur effect comes in three styles:

  • UIBlurEffectStyle.Light
  • UIBlurEffectStyle.ExtraLight
  • UIBlurEffectStyle.Dark

These change the appearance of the blur as shown below:

blur style

Vibrancy Effect

In addition to blur, iOS includes a vibrancy effect (UIVibrancyEffect), which allows content displayed over a blur to remain legible. Vibrancy effects are created from blur effects, and are also displayed using a UIVisualEffectView. Any view the effect should be applied to is added as a subview of the UIVisualEffectView‘s ContentView.

For example, the following code adds a label to be displayed over the blurred view created above:

// vibrancy view
var frame = new Rectangle (10, 10, 100, 50);
var vibrancy = UIVibrancyEffect.FromBlurEffect (blur);
var vibrancyView = new UIVisualEffectView (vibrancy) {
  Frame = frame
};
label = new UILabel {
  Text = "Hello iOS 8!",
  Frame = vibrancyView.Bounds
};
vibrancyView.ContentView.Add (label);
blurView.ContentView.Add (vibrancyView);

When the user scrolls the image, the blur changes and the label’s text is modified dynamically such that it remains readable:

vibrancy

These effects are useful when you want them applied dynamically. Of course, rendering them has some cost, so if you can get the results you are looking for with a static effect, that should be used. However, for creating a level of polish, with a sense of depth on par with iOS itself, it’s nice to now have these features available.

The code from this post is available here.

Discuss this blog post in the Xamarin Forums

 

TwitterFacebookGoogle+LinkedInEmail