Created
September 21, 2016 15:15
-
-
Save emrahgunduz/07cddbb66b651754ee06c7d8f78a5265 to your computer and use it in GitHub Desktop.
Working UIBlurEffect and UIVisualEffectView masking example on iOS10 using Swift 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
class ViewController: UIViewController { | |
func addTheBlurView(data :Data) { | |
let generalFrame = self.view.bounds; | |
let parentView = UIView(frame: generalFrame) | |
self.view.addSubview(parentView) | |
let imageView = UIImageView(frame: parentView.bounds) | |
imageView.image = UIImage(data: data) | |
imageView.contentMode = .scaleAspectFill | |
let maskView = UIView(frame: parentView.bounds) | |
maskView.backgroundColor = UIColor.black | |
maskView.layer.mask = { | |
() -> CALayer in | |
var roundedRect = CGRect( | |
x: 0.0, | |
y: 0.0, | |
width: parentView.bounds.size.width * 0.5, | |
height: parentView.bounds.size.width * 0.5 | |
); | |
roundedRect.origin.x = parentView.frame.size.width / 2 - roundedRect.size.width / 2; | |
roundedRect.origin.y = parentView.frame.size.height / 2 - roundedRect.size.height / 2; | |
let cornerRadius = roundedRect.size.height / 2.0; | |
let path = UIBezierPath(rect: parentView.bounds) | |
let croppedPath = UIBezierPath(roundedRect: roundedRect, cornerRadius: cornerRadius) | |
path.append(croppedPath) | |
path.usesEvenOddFillRule = true | |
let maskLayer = CAShapeLayer() | |
maskLayer.path = path.cgPath; | |
maskLayer.fillRule = kCAFillRuleEvenOdd | |
return maskLayer | |
}() | |
let blurView = UIBlurEffect(style: .light) | |
let effectView = UIVisualEffectView(effect: blurView) | |
effectView.frame = generalFrame | |
effectView.mask = maskView | |
parentView.addSubview(imageView) | |
parentView.addSubview(effectView) | |
} | |
override func viewDidLoad() { | |
debugPrint("Running...") | |
super.viewDidLayoutSubviews(); | |
// Lets load an image first, so blur looks cool | |
let url = URL(string: "https://static.pexels.com/photos/168066/pexels-photo-168066-large.jpeg") | |
URLSession.shared.dataTask(with: url!) { | |
(data, response, error) in | |
if error != nil { | |
print(error) | |
return | |
} | |
DispatchQueue.main.async(execute: { | |
self.addTheBlurView(data: data!) | |
}) | |
}.resume() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment