IOS development-virtual effects of iOS 8, ios development-ios

Source: Internet
Author: User
Tags notification center

IOS development-virtual effects of iOS 8, ios development-ios

In iOS 7, a major change is ubiquitous virtualization, which is particularly eye-catching in the notification center and control center:

However, when developers start to add similar fuzzy effects to their apps, they will find quite serious obstacles. At that time, Apple defined a simple range of device availability, which was not powerful enough to support real-time blurring in third-party applications. And claims that developers are likely to abuse the virtual App, seriously affecting the user experience.

However, savvy and cunning programmers quickly created their own fuzzy Static Image Method to crack real-time fuzzy algorithms.

Most of the solutions are superior. However, the official blur effects added to the developer toolbox in later iOS 8 are not only very efficient, but also amazing in its simplicity.

Tip: If you want to know how to use static fuzzy images to simulate real-time fuzzy search, refer to this blog.

Fuzzy literacy

Certain skills are required to make the blur effect beautiful and efficient. In this section, you will learn the most common fuzzy algorithms and how to use the blur effect to improve the user experience of your App.

How to blur

To blur an image, you need to use a fuzzy algorithm for each pixel in the image. In this way, you can obtain an image after the source image is blurred evenly. Fuzzy algorithms can have many changes in the fuzzy style and complexity. However, in this tutorial, you will use Gaussian blur, the most common and well-known algorithm.

Fuzzy algorithms Usually retrieve each pixel of an image and calculate the gray value of the pixel after blurring Based on the pixel surrounding it. For example, imagine a grid chart as follows:

Each small lattice represents an independent pixel. Each pixel has a value between 1 and 10. If we want to blur the center pixel, We need to calculate the arithmetic mean of the values of the eight surrounding pixels and insert this number into the center pixel value. The result is as follows:

Then, repeat the same operation on each pixel of the source image (Editor's note: the new value of each pixel in the source image should be inserted into the pixel at the corresponding position of the new image to avoid errors, the pixel value of the source image remains unchanged. The source author does not prompt this ).

In the above fuzzy example, only one pixel unit in each direction is used to calculate the pixel value of the new image. You can expand the pixel radius to improve the blur effect of the image, as shown in the following figure:

Tip: Generally, the larger the Blur radius is, the more computation is required for image processing. IOS will hand over most of the image processing work to the GPU for processing to ensure that the main thread will not be stuck.

Fuzzy Design

People are always involuntarily ignored by those precise focus parts. Believe it or not, this is the truth of nature, because the human eyes work like this. The focus mechanism of the eye is like a regulator capturing objects that are too close to you, so that you can feel the depth and distance of everything around you.

In fact, App designers can blur irrelevant content to guide users to focus on those elements that are not blurred. For example, the popular Twitter client is a good example:

The user interface in the background can barely identify, thus providing users with a situational awareness to let them know which position is in the navigation layer. In this example, you only need to select an account to log on and return it to the background layer that is not blurred.

Tip: Although fuzzy recognition can bring a fresh visual experience, you should never use it too much in your App, because excessive use or improper use will distract users or annoy users.

Follow the standard fuzzy design scheme to let users focus on what you want to give, so that you won't easily get it done. You can learn more about the design for iOS in the iOS Human Interface Guidelines Document of the iOS Developer Center.

Start

To understand how to implement fuzzy search, you need to try to add the appropriate fuzzy search effect to an App based on the new greenfairy tale. This App is called Grimm.

This application provides users with a series of fairy tales. When users open a fairy tale, it will display the complete story content on the screen. You can customize the font, text alignment, and color themes for day or night reading.

Now you need to download an initial project, open Grimm. xcodeproj in Xcode, and then open Grimm. storyboard to check the View Controller in the App, as shown below:

You can skip the previous View Controller, because it is only a simple underlying navigation controller in the App. You need to pay attention to the View Controller with serial numbers below:

1. The first controller is StoryListController, which is used to display the list of all fairy tales in the database.

2. When you click a fairy tale, you will switch to this view controller StoryViewController, which will display the title and text content of the selected fairy tale.

3. The final OptionsController is included in StoryViewController and lists some available font, alignment, and color options. You only need to click the settings icon in StoryViewController to display it.

You can see an initial interface as follows:

You can try this application. After selecting the fairy tale, click the ellipsis to call the option view to switch between different fonts and reading modes. This gives you an insight into the basic functions of the user interface.

Tip: You can run this application on a simulator or iOS 8 device other than iPad 2. For performance considerations, Apple restricts the display of fuzzy effects on iPad 2. The App itself can indeed run well on iPad 2, but you will not see any pleasant fuzzy effects.

Manual fuzzy search

Eye-catching students may find that the Objective-C code remains in this project.

This anxiety is not necessary. This Objective-C code is useful in many application projects, and it is quite strong. It serves to access the Grimm-Bridging-Header.h header file in all your Swift files, because there is no need to rewrite one for Swift separately here.

Tip: Swift is designed to be well compatible with Objective-C. In this way, developers, including Apple's own developers, can directly add Swift code to the project without the need to refactor the code. After the header file is connected, you can write the Objective-C code into your Swift file.

Open Grimm \ Categories \ UIImage + ImageEffects in the project resource manager. m file, skip all the preceding annotations to see the code snippet like applyBlurWithRadius: tintColor: saturationDeltaFactor: maskImage:. This tutorial does not overwrite or modify the code from start to end, however, read-only helps you understand the basic functions.

When iOS 7 was released, Apple also provided the UIImage class to demonstrate how to apply static blur to images. This makes full use of the advantages of the Accelerate framework in vector and matrix operations, making it easier to use these calculations in image processing.

ApplyBlurWithRadius: tintColor: saturationDeltaFactor: maskImage: The parameters here include blur radius, saturation, and optional masking images. This method uses a large number of mathematical operations to generate a new processed image.

Get Snapshot

You need to get a snapshot before you use your blur effect. Today, most of your effort will be spent on drawing options at the bottom of the StoryViewController view.

Open the StoryViewController. swift file and find the setOptionsHidden method. Here you will first obtain the entire StoryViewController controller, and then blur it as the background image of the Option interface.

Add the following method to the front of the setOptionsHidden method:

1234567891011 func updateBlur() {  // To avoid the option interface being intercepted, make sure that the option interface is hidden.  optionsContainerView.hidden = true  // Create a new ImageContext for rendering. You do not need to render a full-resolution HD. Using ImageContext can save a lot of computing workload.  UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, true, 1)  // Draw the interface in StoryViewController to ImageContext, because you need to ensure that the option interface is hidden, so you need to wait for the screen to refresh before drawing  self.view.drawViewHierarchyInRect(self.view.bounds, afterScreenUpdates: true)  // Put the ImageContext in a UIImage and then clear the ImageContext  let screenshot = UIGraphicsGetImageFromCurrentImageContext()  UIGraphicsEndImageContext()}

After clicking the ellipsis, you need to call an updateBlur method to blur it. In this way, you need to add the following code at the beginning of the setOptionsHidden method:

123 if !hidden {  updateBlur()}

Before proceeding, check whether you have captured the image you want to cut.

Find the UIGraphicsEndImageContext () line in the source code of the updateBlur method added in the previous step, add a breakpoint, build and run it, select a fairy tale, and open it.

Once the fairy tale is opened, click the ellipsis to trigger the breakpoint. Expand the screenshot variable in the debugging column and select some variables nested in the following:

Press the Space key to open Quick Look. You should see a non-HD story bar. As follows:

Note that UINavigationController is not included in any element, because the view in the story list exists as the background image of UINavigationController, and the navigation controller is located outside the region.

Now you can take a correct snapshot. You can use the UIImage class we mentioned earlier to blur your start.

Blur your Snapshot

Open the StoryViewController. swift file, find the updateBlur method you just changed, and add this line of code below the last line of UIGraphicsEndImageContext:

1 let blur = screenshot.applyLightEffect()

Move the breakpoint you just added to the file, like this:

Tip: You can drag the breakpoint up and down in the scroll slot.

Build and run. Open a fairy tale, click the ellipsis in the navigator, find the blur variable in the debugging bar, and open Quick Look with spaces.

Wait ...... There seems to be nothing in blur? Where have you been?

You didn't see anything because your breakpoint is placed on the line set by the blur variable, so Xcode will stop at the step before this line is executed.

To execute the highlighted line, you can tap F6 or as shown in, and click to execute the next step:

Now you can expand the blur variable, select the some variable below, and press the Space key to call Quick Look to view your blurred image:

Tip: LLDB (Xcode debugger) is sometimes not suitable for Swift, so you may need to click twice to execute the next step to display a certain variable.

Now you can get a snapshot and blur it. The next step is to add the blurred image to the App.

Display blurred images in the view

Open the StoryViewController. swift file and add the following line to the beginning of the heap Code defined by the attribute:

1 var blurView = UIImageView()

You can initialize a UIImageView for each StoryViewController instance.

Find the viewDidLoad method and add the following paragraph at the end of the method:

1 optionsContainerView.subviews[0].insertSubview(blurView, atIndex:0)

In the Grimm. storyboard, OptionsController is placed into a view container so that you can click the ellipsis to display it. Because you do not need to directly use the layer where OptionsController is located, You need to obtain the subview of this container. In this case, this view only happens to belong to OptionsController. Finally, you need to add the fuzzy blurview as the subview to the bottom of the view stack to ensure that it is under all other views.

Find the updateBlur method in the StoryViewController. swift file and add the following code at the end:

123 blurView.frame = optionsContainerView.boundsblurView.image = bluroptionsContainerView.hidden = false

Because blurView is not set in Storyboard, it will have a CGRectZero image unless you have set it manually. Of course, you can also set the attributes of the image you just generated.

Note that you have previously set optionsContainerView to an invisible hidden state. Remember to set optionsContainerView to visible at the end of the virtualized method.

Cancel the breakpoint you set, build and run it. After selecting a fairy tale, click the settings option. Pay attention to the blur effect in the scope of it, as shown below:

This virtualization seems a little tricky, because it does not seem very similar to the text below?

By default, UIImageView resets the image size to make sure it is used with the image in the view. That is to say, the larger imaginary image has been compressed. Therefore, this effect is achieved.

To correct this error, you need to change the contentMode attribute of UIImageView to a value other than the default UIViewContentMode. ScaleToFill.

In updateBlur, set the blurView line and paste the following code:

1 blurView.contentMode = .Bottom

UIViewContentMode. Bottom indicates to keep the original image size, instead of being as large as the middle and lower part of the UIImageView source image.

Build and run. Now let's see what the effects of virtualization are?

You need to consider one more thing before you prepare to use static fuzzy match. Rotate your device or Virtual Machine (command + left/right arrow keys ), you can see that the view size is not reset.

Because all your text uses an automatic layout, it is no longer useful. You need to take a snapshot and update blurView after rotation.

This is easy to implement. In StoryViewController. swift, rewrite the following method in the response:

12345678 override func viewWillTransitionToSize(size: CGSize,  withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {  // The animateAlongsideTransition method can make the changes when you rotate the screen more dynamic and clean up after the rotation is complete. What you only need is the latter, because you also need to capture a frame chart after optionsViewController rotation.  coordinator.animateAlongsideTransition(nil, completion: { context in    // Update blurView after rotation, so that the new layout will be used.    self.updateBlur()  })}

After building and running it, try to change the angle of the device or simulator and you will find a new layout:

The size of the fuzzy range is correct, but it is not enough. You can see that the virtual part has not changed.

Based on the above experience, you should also know how to modify it. Later, iOS 8 provides a tool for dynamic virtual generation. The use of real-time fuzzy effects in applications has been a long story since the solutions that developers have developed on iOS 7.

Blur effects on iOS 8

IOS 8 provides a complete set of practical virtual tools. UIBlurEffect, a subclass of UIVisualEffect, is of interest to us. UIBlurEffect provides the beautiful blur you see in the navigation bar, notification center, and control center. You can also use this effect in your App.

Add UIBlurEffect

Open the StoryViewController. swift file and find the setOptionsHidden method. if you have written updateBlur In the first if condition branch, comment it out. The modification is as follows:

Even though you have done this, you cannot completely ensure that blurview is not added to the scene. comment out the following line:

1 optionsContainerView.subviews[0].insertSubview(blurView, atIndex:0)

Tip: do not simply delete the code. You just need to comment out the code, which makes it easier for you to review the differences. If you don't have any idea about the fuzzy code you manually add, you can delete them instead of comments.

After building and running the SDK, you will find that the remaining parts can run normally except your blur.

Open Grimm. storyboard, find Options Controller Scene, select view, expand Attributes Inspector, and change the view background to Clear color, as shown below:

Open the OptionsController. swift file and add the following code to the viewDidLoad method. The location will be next to the optionsView you added earlier:

1234567 // Create a UIBlurEffect with the UIBlurEffectStyle. Light style and set the effect to be applied. Other effects include UIBlurEffectStyle. ExtraLight and UIBlurEffectStyle. Dark.let blurEffect = UIBlurEffect(style: .Light)// Create a uivisualiztview and set the expected effect for it. Uivisualiztview is a subclass of UIView. It is used to define and display complex virtual effects separately.let blurView = UIVisualEffectView(effect: blurEffect)// Lift the blurView adaptive mask size limit. You can also manually add the limit later, and then move it to the bottom of the view stack. If you add it to the top, it will cover all the controllers.blurView.setTranslatesAutoresizingMaskIntoConstraints(false)view.insertSubview(blurView, atIndex: 0)

Now you need to make sure that your blurView can be properly laid out.

Still in viewDidLoad, write the following code before calling addConstraints:

123456 constraints.append(NSLayoutConstraint(item: blurView,  attribute: .Height, relatedBy: .Equal, toItem: view,  attribute: .Height, multiplier: 1, constant: 0))constraints.append(NSLayoutConstraint(item: blurView,  attribute: .Width, relatedBy: .Equal, toItem: view,  attribute: .Width, multiplier: 1, constant: 0))

These parameter restrictions make the blurView image always adapt to OptionsController.

Build and run. Open the fairy tale, click the ellipsis, and then slide the text behind it. The imaginary part can be changed in Real Time:

Now you have an App capable of dynamic rendering of virtual, not only looks nice, but you still use the core functions of iOS.

Add Vibrancy

The effects of virtualization are quite good-but Apple has improved it as before. By using UIVibrancyEffect and UIVisualEffectView, you can adjust the text color to make the App look more colorful.

The following figure shows how to make your labels and icons more comfortable on the screen when the background image of Vibrancy is identical:

The labels and buttons on the left are usually displayed, while those on the right are the results after Vibrancy is applied.

Tip: UIVibrancyEffect must be added to the uivisualizer tview configured with UIBlurEffect. Otherwise, no virtualized image will apply the Vibrancy effect.

Find viewDidLoad in the OptionsController. swift file and add the following code before the Automatic Layout constraints:

123456789 // Use the blurEffect you set before to build UIVibrancyEffect. UIVibrancyEffect is another subclass of UIVisualEffect.let vibrancyEffect = UIVibrancyEffect(forBlurEffect: blurEffect)// Create a uivisualpolictview to apply the Vibrancy effect. This process happens to be the same as generating a fuzzy image. Because you are using automatic layout, you need to change the adaptive size to false here.let vibrancyView = UIVisualEffectView(effect: vibrancyEffect)vibrancyView.setTranslatesAutoresizingMaskIntoConstraints(false)// Add optionsView to the contentView attribute of vibrancyView to ensure that the Vibrancy effect is applied to all control views.vibrancyView.contentView.addSubview(optionsView)// Add vibrancyView to the blurView contentView to complete the effect.blurView.contentView.addSubview(vibrancyView)

The last thing is to set an automatic layout limit for the Vibrancy view so that it can maintain a high width with your controller view.

Add the following restrictions to the end of the viewDidLoad method:

12345678 constraints.append(NSLayoutConstraint(item: vibrancyView,  attribute: .Height, relatedBy: .Equal,  toItem: view, attribute: .Height,  multiplier: 1, constant: 0))constraints.append(NSLayoutConstraint(item: vibrancyView,  attribute: .Width, relatedBy: .Equal,  toItem: view, attribute: .Width,  multiplier: 1, constant: 0))

Build and run the program, and call out the setting options to see the effect of your Vibrancy.

Unless your eyes are also high-split screens, it's really hard to clear tags and controllers, so what exactly happened?

This is actually the case because the style you use for blurView is UIBlurEffectStyle. Light, so it is white. In this way, the expected Vibrancy effect will not be generated.

In the viewDidLoad method, change the initialization of blurEffect to the following:

1 let blurEffect = UIBlurEffect(style: .Dark)

This changes and adds the color contrast between the Fuzzy View and the background.

After building and running, you can see a satisfactory Vibrancy effect.

More

You can download the completed project here.

Now you know how to blur an image manually, how to perform real-time fuzzy rendering, and how to simply use uivisualiztviews on your App.

The Blur technique you can use is limited to static images, so images are not very vivid and cannot be updated in real time. However, UIBlurEffect can be used for real-time updates, so that you can use this effect to do some wonderful things, such as animation.

At the same time, you may also attempt to blur everything-think about what we mentioned at the beginning of the tutorial-Use of virtualization should be appropriate and restrained. Of course, this is also true for Vibrancy.

(Press: This is a tutorial on iOS 8 virtual effects from Ray Wenderlich. Here is just an overview. If you want to learn more, refer to the iOS 8 Feast topic of the website)


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.