Created
September 30, 2019 02:13
-
-
Save siavashalipour/630163f6d96db109b1192520076788a4 to your computer and use it in GitHub Desktop.
Swift crop a whole inside Blurred UIView
This file contains hidden or 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
func createOverlay(frame: CGRect, | |
xOffset: CGFloat, | |
yOffset: CGFloat, | |
radius: CGFloat) -> UIView { | |
// Step 1 | |
// let overlayView = UIView(frame: frame) | |
// overlayView.backgroundColor = UIColor.black.withAlphaComponent(0.6) | |
let blur = UIBlurEffect(style: .regular) | |
let blurViewTop = UIVisualEffectView(effect: blur) | |
blurViewTop.frame = view.bounds//CGRect(x: 0, y: 0, width: view.bounds.width, height: (view.bounds.height / 2) - 64) | |
blurViewTop.autoresizingMask = [.flexibleWidth, .flexibleHeight] | |
let overlayView = blurViewTop | |
// Step 2 | |
let path = CGMutablePath() | |
path.addRect(CGRect(x: (frame.width - kSizeOfTheRect) / 2, y: frame.height / 2 - kSizeOfTheRect, width: kSizeOfTheRect, height: kSizeOfTheRect)) | |
// remove the above line and add uncomment the line below to have circle whole | |
// path.addArc(center: CGPoint(x: xOffset, y: yOffset), | |
// radius: radius, | |
// startAngle: 0.0, | |
// endAngle: 2.0 * .pi, | |
// clockwise: false) | |
path.addRect(CGRect(origin: .zero, size: overlayView.frame.size)) | |
// Step 3 | |
let maskLayer = CAShapeLayer() | |
maskLayer.backgroundColor = UIColor.black.cgColor | |
maskLayer.path = path | |
// For Swift 4.2 | |
maskLayer.fillRule = .evenOdd | |
// Step 4 | |
overlayView.layer.mask = maskLayer | |
overlayView.clipsToBounds = true | |
return overlayView | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment