44

Blur Effect iOS Tutorial

 5 years ago
source link: https://www.tuicool.com/articles/hit/7vERFve
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

The UIVisualEffectView class can be used to apply visual effects to a view. In this tutorial a darkened blur effect will be applied to an image. This tutorial is made with Xcode 10 and built for iOS 12.

Project Setup

Open Xcode and create a new Single View App.

n2YnEbu.png!web

For product name, use iOSBlurEffectTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.

z2eeyu7.png!web

For this tutorial we need a image to apply the blur effect to. Download the zipfile containing the image. Open the Assets Library and drag the image into it.

Go to the Storyboard .  Drag an Image View to the Storyboard. Go to the Size Inspector and make the Height and Width 256 points.

qMVfEzF.png!web

Go to the Attributes Inspector and in the ImageView section choose the image file at the Image field.

YbYJVjB.png!web

Drag a Button to the Storyboard and place it below the Image View. Give the button a title of "Blur".  Select the Resolve Auto Layout Issues button and select Reset to Suggested Constraints.

yiE3aiZ.png!web

The Storyboard should look like this.

qAN3Q3Q.png!web

Open the Assistant Editor and make sure the ViewController.swift file is visible. Ctrl + drag from the Image View to the ViewController class and create the following Outlet.

f2Ijmma.png!web

Ctrl + drag from the Button to the ViewController class and create the following Action.

RzUV7nV.png!web

Go to the ViewController.swift file. Change the blurImage Action method to

@IBAction func blurImage(_ sender: Any) {
    // 1
    let darkBlur = UIBlurEffect(style: .dark)
    // 2
    let blurView = UIVisualEffectView(effect: darkBlur)
    blurView.frame = imageView.bounds
    // 3
    imageView.addSubview(blurView)
}
  1. the dark blur effect is assigned to the darkBlur variable.

  2. The VisualEffectView is created containing the darkened blur effect.

  3. the blurView is added as a subview of the Image View.

Build and Runthe project, click the Blur button and the darkened blur affect will be applied to the image.

UFryQji.png!web

You can download the source code of the iOSBlurEffectTutorial at the ioscreator repository on Github .


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK