Creating a UIView programmatically - ios

If I create a UIView with a frame like - UIView(frame:..) AND also set constraints on this view will the frame dimensions take precedence over the constraints? Will iOS runtime ignore the constraints?
I created a UIView in viewDidLoad() with a frame and attached constraints to this view. However the constraints are not being enforced at all and the view is rendered in the frame passed to the initializer.
[Edit]
My code is below. I am trying to add an overlay to AVCaptureVideoPreviewLayer (viewPreviewLayer) programatically on top of a UIView (previewContainer, configured with constraints on storyboard) that covers the entire screen.
....
var videoPreviewLayer:AVCaptureVideoPreviewLayer!
#IBOutlet weak var previewContainer: UIView!
....
override func viewDidLoad() {
.....
self.configurePreviewLayer()
}
override func viewDidLayoutSubviews() {
print("viewDidLayoutSubviews")
super.viewDidLayoutSubviews()
self.videoPreviewLayer.frame = self.previewContainer.bounds
}
func configurePreviewLayer() {
print("configurePreviewLayer()")
self.videoPreviewLayer = AVCaptureVideoPreviewLayer(session: self.captureSession)
self.videoPreviewLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
self.previewContainer.layer.addSublayer(self.videoPreviewLayer)
configureBlurView()
}
func configureBlurView() {
print("configureBlurView()")
// Blur View
let viewFinderRadius:CGFloat = self.view.bounds.width / 2.0 - 16.0
print("configureBlurView:\(self.previewContainer.bounds.size.height)")
let blurView = createOverlay(frame:self.previewContainer.bounds,xOffset: self.view.bounds.size.width / 2.0, yOffset: self.view.bounds.size.height / 2.0, radius: viewFinderRadius)
blurView.translatesAutoresizingMaskIntoConstraints = false
self.previewContainer.addSubview(blurView)
self.blurView = blurView
blurView.leftAnchor.constraint(equalTo: self.previewContainer.leftAnchor).isActive = true
blurView.topAnchor.constraint(equalTo:self.previewContainer.topAnchor).isActive = true
blurView.rightAnchor.constraint(equalTo:self.previewContainer.rightAnchor).isActive = true
blurView.bottomAnchor.constraint(equalTo:self.previewContainer.bottomAnchor).isActive = true
}
func createOverlay(frame : CGRect, xOffset: CGFloat, yOffset: CGFloat, radius: CGFloat) -> UIView
{
let overlayView = UIView(frame: frame)
overlayView.backgroundColor = UIColor.black.withAlphaComponent(0.7)
let path = CGMutablePath()
path.addArc(center: CGPoint(x: xOffset, y: yOffset), radius: radius, startAngle: 0.0, endAngle: 2.0 * CGFloat.pi, clockwise: false)
path.addRect(CGRect(origin: .zero, size: overlayView.frame.size))
let maskLayer = CAShapeLayer()
maskLayer.backgroundColor = UIColor.black.cgColor
maskLayer.path = path
maskLayer.fillRule = kCAFillRuleEvenOdd
overlayView.layer.mask = maskLayer
overlayView.clipsToBounds = true
return overlayView
}
Here is how the rendered screen looks (As you can see the overlay doesn't cover the entire screen or in other words the entire bounds of previewContainer) -
[Update]
I may have found the culprit. It is this piece of code that masks the overlay -
let path = CGMutablePath()
path.addArc(center: CGPoint(x: xOffset, y: yOffset), radius: radius, startAngle: 0.0, endAngle: 2.0 * CGFloat.pi, clockwise: false)
path.addRect(CGRect(origin: .zero, size: overlayView.frame.size))
let maskLayer = CAShapeLayer()
maskLayer.backgroundColor = UIColor.black.cgColor
maskLayer.path = path
maskLayer.fillRule = kCAFillRuleEvenOdd
overlayView.layer.mask = maskLayer
If I remove the above mask everything is rendered properly. Now I need to figure out how to draw that mask (view finder for the camera).

Will iOS runtime ignore the constraints?
If the constraints are set properly, no: it will ignore the frame. However, you have not shown what you did, so it is impossible to say what you are seeing and why.

Related

iOS (Swift) Annuls-shaped UIBezierPath for CAShapeLayer

I'm trying to make an annulus-shaped UIBezierPath to use as the path of a CAShapeLayer
The following produces a circular path:
let radius = 100.0
let circularPath = UIBezierPath(arcCenter: .zero, radius: radius, startAngle: 0.0, endAngle: 2.0 * .pi, clockwise: true)
let layer = CAShapeLayer()
layer.path = circularPath.cgPath
However, I want an annuls-shaped UIBezierPath that fills between radius and say outerRadius = radius + 10.
If this is what you're going for ("Annulus" shape):
You can achieve it by creating an Oval path and appending a smaller Oval path.
You can run this directly in a Playground page to get that result:
import PlaygroundSupport
import UIKit
class AnnulusView: UIView {
private var annulusLayer: CAShapeLayer!
private var annulusWidth: CGFloat = 10.0
private var fillColor: UIColor = .red
override func layoutSubviews() {
super.layoutSubviews()
if annulusLayer == nil {
annulusLayer = CAShapeLayer()
layer.addSublayer(annulusLayer)
}
let r = bounds
let outerPath = UIBezierPath(ovalIn: r)
let innerPath = UIBezierPath(ovalIn: r.insetBy(dx: annulusWidth, dy:annulusWidth))
outerPath.append(innerPath)
outerPath.usesEvenOddFillRule = true
annulusLayer.path = outerPath.cgPath
annulusLayer.fillRule = kCAFillRuleEvenOdd
annulusLayer.fillColor = fillColor.cgColor
// if you want a border
// annulusLayer.lineWidth = 1
// annulusLayer.strokeColor = UIColor.black.cgColor
}
}
class TestingViewController: UIViewController {
override public var preferredContentSize: CGSize {
get { return CGSize(width: 400, height: 400) }
set { super.preferredContentSize = newValue }
}
var theAnnulusView: AnnulusView = {
let v = AnnulusView()
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
view.addSubview(theAnnulusView)
// make the Annulus view 100x100 centered in this view
NSLayoutConstraint.activate([
theAnnulusView.widthAnchor.constraint(equalToConstant: 100),
theAnnulusView.heightAnchor.constraint(equalToConstant: 100),
theAnnulusView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
theAnnulusView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
])
}
}
let viewController = TestingViewController()
PlaygroundPage.current.liveView = viewController
Check out this, It might be helpful.
If you need a full circle, you need to adjust arcCenter
let width:CGFloat = 10
let radius:CGFloat = 100.0-width/2
let circularPath = UIBezierPath(arcCenter: .zero, radius: radius, startAngle: 0.0, endAngle: 2.0 * .pi, clockwise: true)
let layer = CAShapeLayer()
layer.lineWidth = width
layer.path = circularPath.cgPath

Creating a thin black circle (unfilled) within a filled white circle (UIButton)

I'm trying to replicate the default camera button on iOS devices:
I'm able to create a white circular button with black button within it. However, the black button is also filled, instead of just being a thin circle.
This is what I have (most of it has been copied from different sources and put together, so the code isn't efficient)
The object represents the button,
func applyRoundCorner(_ object: AnyObject) {
//object.layer.shadowColor = UIColor.black.cgColor
//object.layer.shadowOffset = CGSize(width: 0.0, height: 2.0)
object.layer.cornerRadius = (object.frame.size.width)/2
object.layer.borderColor = UIColor.black.cgColor
object.layer.borderWidth = 5
object.layer.masksToBounds = true
//object.layer.shadowRadius = 1.0
//object.layer.shadowOpacity = 0.5
var CircleLayer = CAShapeLayer()
let center = CGPoint (x: object.frame.size.width / 2, y: object.frame.size.height / 2)
let circleRadius = object.frame.size.width / 6
let circlePath = UIBezierPath(arcCenter: center, radius: circleRadius, startAngle: CGFloat(M_PI), endAngle: CGFloat(M_PI * 2), clockwise: true)
CircleLayer.path = circlePath.cgPath
CircleLayer.strokeColor = UIColor.black.cgColor
//CircleLayer.fillColor = UIColor.blue.cgColor
CircleLayer.lineWidth = 1
CircleLayer.strokeStart = 0
CircleLayer.strokeEnd = 1
object.layer.addSublayer(CircleLayer)
}
Basic Approach
You could do it like this (for the purpose of demonstration, I would do the button programmatically, using a playground):
let buttonWidth = 100.0
let button = UIButton(frame: CGRect(x: 0, y: 0, width: buttonWidth, height: buttonWidth))
button.backgroundColor = .white
button.layer.cornerRadius = button.frame.width / 2
Drawing Part:
So, after adding the button and do the desired setup (make it circular), here is part of how you could draw a circle in it:
let circlePath = UIBezierPath(arcCenter: CGPoint(x: buttonWidth / 2,y: buttonWidth / 2), radius: 40.0, startAngle: 0, endAngle: CGFloat.pi * 2, clockwise: true)
let circleLayer = CAShapeLayer()
circleLayer.path = circlePath.cgPath
circleLayer.fillColor = UIColor.clear.cgColor
circleLayer.strokeColor = UIColor.black.cgColor
circleLayer.lineWidth = 2.5
// adding the layer into the button:
button.layer.addSublayer(circleLayer)
Probably, circleLayer.fillColor = UIColor.clear.cgColor is the part you missing 🙂.
Therefore:
Back to your case:
Aside Bar Tip:
For implementing applyRoundCorner, I would suggest to let it has only the job for rounding the view, and then create another function to add the circle inside the view. And that's for avoiding any naming conflict, which means that when reading "applyRoundCorner" I would not assume that it is also would add circle to my view! So:
func applyRoundedCorners(for view: UIView) {
view.layer.cornerRadius = view.frame.size.width / 2
view.layer.borderColor = UIColor.white.cgColor
view.layer.borderWidth = 5.0
view.layer.masksToBounds = true
}
func drawCircle(in view: UIView) {
let circlePath = UIBezierPath(arcCenter: CGPoint(x: view.frame.size.width / 2,y: view.frame.size.width / 2),
radius: view.frame.size.width / 2.5,
startAngle: 0,
endAngle: CGFloat.pi * 2,
clockwise: true)
let shapeLayer = CAShapeLayer()
shapeLayer.path = circlePath.cgPath
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = UIColor.black.cgColor
shapeLayer.lineWidth = 2.5
button.layer.addSublayer(shapeLayer)
}
and now:
applyRoundedCorners(for: button)
drawCircle(in: button)
That's seems to be better. From another aspect, consider that you want to make a view to be circular without add a circle in it, with separated methods you could simply applyRoundedCorners(for: myView) without the necessary of adding a circle in it.
Furthermore:
As you can see, I changed AnyObject to UIView, it seems to be more logical to your case. So here is a cool thing that we could do:
extension UIView {
func applyRoundedCorners(for view: UIView) {
view.layer.cornerRadius = view.frame.size.width / 2
view.layer.borderColor = UIColor.white.cgColor
view.layer.borderWidth = 5.0
view.layer.masksToBounds = true
}
func drawCircle(in view: UIView) {
let circlePath = UIBezierPath(arcCenter: CGPoint(x: view.frame.size.width / 2,y: view.frame.size.width / 2),
radius: view.frame.size.width / 2.5,
startAngle: 0,
endAngle: CGFloat.pi * 2,
clockwise: true)
let shapeLayer = CAShapeLayer()
shapeLayer.path = circlePath.cgPath
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = UIColor.black.cgColor
shapeLayer.lineWidth = 2.5
button.layer.addSublayer(shapeLayer)
}
}
Now both applyRoundedCorners and drawCircle are implicitly included to the UIView (which means UIButton), instead of passing the button to these functions, you would be able to:
button.applyRoundedCorners()
button.drawCircle()
You just need to add circle Shape layer with lesser width and height
Try this code
func applyRoundCorner(_ object: UIButton) {
object.layer.cornerRadius = (object.frame.size.width)/2
object.layer.borderColor = UIColor.black.cgColor
object.layer.borderWidth = 5
object.layer.masksToBounds = true
let anotherFrame = CGRect(x: 12, y: 12, width: object.bounds.width - 24, height: object.bounds.height - 24)
let circle = CAShapeLayer()
let path = UIBezierPath(arcCenter: object.center, radius: anotherFrame.width / 2, startAngle: 0, endAngle: .pi * 2, clockwise: true)
circle.path = path.cgPath
circle.strokeColor = UIColor.black.cgColor
circle.lineWidth = 1.0
circle.fillColor = UIColor.clear.cgColor
object.layer.addSublayer(circle)
}
Note: Change frame value according to your requirements and best user experience
Output
I have no doubt there are a million different ways to approach this problem, this is just one...
I started with a UIButton for simplicity and speed, I might consider actually starting with a UIImage and simply setting the image properties of the button, but it would depend a lot on what I'm trying to achieve
internal extension FloatingPoint {
var degreesToRadians: Self { return self * .pi / 180 }
var radiansToDegrees: Self { return self * 180 / .pi }
}
class RoundButton: UIButton {
override func draw(_ rect: CGRect) {
makeButtonImage()?.draw(at: CGPoint(x: 0, y: 0))
}
func makeButtonImage() -> UIImage? {
let size = bounds.size
UIGraphicsBeginImageContext(CGSize(width: size.width, height: size.height))
defer {
UIGraphicsEndImageContext()
}
guard let ctx = UIGraphicsGetCurrentContext() else {
return nil
}
let center = CGPoint(x: size.width / 2.0, y: size.height / 2.0)
// Want to "over fill" the image area, so the mask can be applied
// to the entire image
let radius = min(size.width / 2.0, size.height / 2.0)
let innerRadius = radius * 0.75
let innerCircle = UIBezierPath(arcCenter: center,
radius: innerRadius,
startAngle: CGFloat(0.0).degreesToRadians,
endAngle: CGFloat(360.0).degreesToRadians,
clockwise: true)
// The color doesn't matter, only it's alpha level
UIColor.red.setStroke()
innerCircle.lineWidth = 4.0
innerCircle.stroke(with: .normal, alpha: 1.0)
let circle = UIBezierPath(arcCenter: center,
radius: radius,
startAngle: CGFloat(0.0).degreesToRadians,
endAngle: CGFloat(360.0).degreesToRadians,
clockwise: true)
UIColor.clear.setFill()
ctx.fill(bounds)
UIColor.white.setFill()
circle.fill(with: .sourceOut, alpha: 1.0)
return UIGraphicsGetImageFromCurrentImageContext()
}
}
nb: This is unoptimised! I would consider caching the result of makeButtonImage and invalidate it when the state/size of the button changes, just beware of that
Why is this approach any "better" then any other? I just want to say, it's not, but what it does create, is a "cut out" of the inner circle
It's a nitpick on my part, but I think it looks WAY better and is a more flexible solution, as you don't "need" a inner circle stroke color, blah, blah, blah
The solution makes use of the CoreGraphics CGBlendModes
Of course I might just do the whole thing in PaintCodeApp and be done with it

Thin border when using CAShapeLayer as mask for CAShapeLayer

In Swift, I have two semi-transparent circles, both of which are CAShapeLayer. Since they are semi-transparent, any overlap between them becomes visible like so:
Instead, I want them to visually "merge" together. The solution I have tried is to use circle 2 as a mask for circle 1, therefore cutting away the overlap.
This solution is generally working, but I get a thin line on the outside of circle 2:
My question: How can I get rid of the thin, outside line on the right circle? Why is it even there?
The code is as follows (Xcode playground can be found here):
private let yPosition: CGFloat = 200
private let circle1Position: CGFloat = 30
private let circle2Position: CGFloat = 150
private let circleDiameter: CGFloat = 200
private var circleRadius: CGFloat { return self.circleDiameter/2.0 }
override func loadView() {
let view = UIView()
view.backgroundColor = .black
self.view = view
let circle1Path = UIBezierPath(
roundedRect: CGRect(
x: circle1Position,
y: yPosition,
width: circleDiameter,
height: circleDiameter),
cornerRadius: self.circleDiameter)
let circle2Path = UIBezierPath(
roundedRect: CGRect(
x: circle2Position,
y: yPosition,
width: circleDiameter,
height: circleDiameter),
cornerRadius: self.circleDiameter)
let circle1Layer = CAShapeLayer()
circle1Layer.path = circle1Path.cgPath
circle1Layer.fillColor = UIColor.white.withAlphaComponent(0.6).cgColor
let circle2Layer = CAShapeLayer()
circle2Layer.path = circle2Path.cgPath
circle2Layer.fillColor = UIColor.white.withAlphaComponent(0.6).cgColor
self.view.layer.addSublayer(circle1Layer)
self.view.layer.addSublayer(circle2Layer)
//Create a mask from the surrounding rectangle of circle1, and
//then cut out where it overlaps circle2
let maskPath = UIBezierPath(rect: CGRect(x: circle1Position, y: yPosition, width: circleDiameter, height: circleDiameter))
maskPath.append(circle2Path)
maskPath.usesEvenOddFillRule = true
maskPath.lineWidth = 0
let maskLayer = CAShapeLayer()
maskLayer.path = maskPath.cgPath
maskLayer.fillColor = UIColor.black.cgColor
maskLayer.fillRule = kCAFillRuleEvenOdd
circle1Layer.mask = maskLayer
}
If both CAShapeLayers have the same alpha value, you could place them inside a new parent CALayer then set the alpha of the parent instead.

Drawing circles proportionally to containing view in swift

I am trying to draw 3 circles inside my 3 views but only the top view circle is drawn even doth the code is the same. I can't seem to understand where is the problem, that's why the two other circle are not there?
class ViewController: UIViewController {
///Views used to display the progress view
var topView: CircleView!
var middleView: CircleView!
var bottomView: CircleView!
override func viewDidLoad() {
super.viewDidLoad()
createThreeViews()
}
func createThreeViews(){
let viewHeight = self.view.bounds.height
let viewWidth = self.view.bounds.width
//Top View
let topTimerFrame = CGRect(x: 0, y: 0, width: viewWidth, height: 3/6 * viewHeight)
topView = CircleView(frame: topTimerFrame)
topView.backgroundColor = UIColor.redColor()
//Middle View
let middleTimerFrame = CGRect(x: 0, y: topTimerFrame.height, width: viewWidth, height: 2/6 * viewHeight)
middleView = CircleView(frame: middleTimerFrame)
middleView.backgroundColor = UIColor.blueColor()
//Bottom view
let bottomTimerFrame = CGRect(x: 0, y: topTimerFrame.height + middleTimerFrame.height, width: viewWidth, height: 1/6 * viewHeight)
bottomView = CircleView(frame: bottomTimerFrame)
bottomView.backgroundColor = UIColor.greenColor()
//add top circle and set constraint
self.view.addSubview(topView)
//add middle circle and set constraints
self.view.addSubview(middleView)
//add bottom circle and set constraints
self.view.addSubview(bottomView)
}
}
//class used to create the views and draw circles in them
class CircleView: UIView {
let π:CGFloat = CGFloat(M_PI)
let circle = CAShapeLayer()
var secondLayerColor: UIColor = UIColor.whiteColor()
//custom initializer
override init(frame: CGRect) {
super.init(frame: frame)
userInteractionEnabled = true
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
userInteractionEnabled = true
setup()
}
func setup() {
//draw the circle and add to layer
circle.frame = bounds
circle.lineWidth = CGFloat(4)
circle.fillColor = UIColor.whiteColor().CGColor
circle.strokeEnd = 1
layer.addSublayer(circle)
setupShapeLayer(circle)
}
override func layoutSubviews() {
super.layoutSubviews()
setupShapeLayer(circle)
}
func setupShapeLayer(shapeLayer: CAShapeLayer) {
shapeLayer.frame = bounds
let radius = frame.height/2 - circle.lineWidth/2
let startAngle = CGFloat(0)
let endAngle = 2*Ï€
let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: false)
shapeLayer.path = path.CGPath
}
}
You are drawing your circle with an offset to your frame (the other two circles are drawn, but outside of the frames).
Change:
let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: false)
to:
let path = UIBezierPath(arcCenter: CGPoint(x: center.x , y: frame.height/2) , radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: false)
Btw. you probably want to change setupShapeLayer(circle) in setup() to setNeedsLayout(); layoutIfNeeded(), otherwise it will be drawn twice the first time.

How do I create a UIView with a transparent circle inside (in swift)?

I want to create a view that looks like this:
I figure what I need is a uiview with some sort of mask, I can make a mask in the shape of a circle using a UIBezierpath, however I cannot invert this makes so that it masks everything but the circle. I need this to be a mask of a view and not a fill layer because the view that I intend to mask has a UIBlurEffect on it. The end goal is to animate this UIView overtop of my existing views to provide instruction.
Please note that I am using swift. Is there away to do this? If so, how?
Updated again for Swift 4 & removed a few items to make the code tighter.
Please note that maskLayer.fillRule is set differently between Swift 4 and Swift 4.2.
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)
// Step 2
let path = CGMutablePath()
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.0
maskLayer.fillRule = kCAFillRuleEvenOdd
// For Swift 4.2
maskLayer.fillRule = .evenOdd
// Step 4
overlayView.layer.mask = maskLayer
overlayView.clipsToBounds = true
return overlayView
}
A rough breakdown on what is happening:
Create a view sized to the specified frame, with a black background set to 60% opacity
Create the path for drawing the circle using the provided starting point and radius
Create the mask for the area to remove
Apply the mask & clip to bounds
The following code snippet will call this and place a circle in the middle of the screen with radius of 50:
let overlay = createOverlay(frame: view.frame,
xOffset: view.frame.midX,
yOffset: view.frame.midY,
radius: 50.0)
view.addSubview(overlay)
Which looks like this:
You can use this function to create what you need.
func createOverlay(frame : CGRect)
{
let overlayView = UIView(frame: frame)
overlayView.alpha = 0.6
overlayView.backgroundColor = UIColor.blackColor()
self.view.addSubview(overlayView)
let maskLayer = CAShapeLayer()
// Create a path with the rectangle in it.
var path = CGPathCreateMutable()
let radius : CGFloat = 50.0
let xOffset : CGFloat = 10
let yOffset : CGFloat = 10
CGPathAddArc(path, nil, overlayView.frame.width - radius/2 - xOffset, yOffset, radius, 0.0, 2 * 3.14, false)
CGPathAddRect(path, nil, CGRectMake(0, 0, overlayView.frame.width, overlayView.frame.height))
maskLayer.backgroundColor = UIColor.blackColor().CGColor
maskLayer.path = path;
maskLayer.fillRule = kCAFillRuleEvenOdd
// Release the path since it's not covered by ARC.
overlayView.layer.mask = maskLayer
overlayView.clipsToBounds = true
}
Adjust the radius and xOffset and yOffset to change the radius and position of the circle.
For Swift 3, here is rakeshbs' answer formatted so it returns the UIView needed:
func createOverlay(frame : CGRect, xOffset: CGFloat, yOffset: CGFloat, radius: CGFloat) -> UIView
{
let overlayView = UIView(frame: frame)
overlayView.alpha = 0.6
overlayView.backgroundColor = UIColor.black
// Create a path with the rectangle in it.
let path = CGMutablePath()
path.addArc(center: CGPoint(x: xOffset, y: yOffset), radius: radius, startAngle: 0.0, endAngle: 2 * 3.14, clockwise: false)
path.addRect(CGRect(x: 0, y: 0, width: overlayView.frame.width, height: overlayView.frame.height))
let maskLayer = CAShapeLayer()
maskLayer.backgroundColor = UIColor.black.cgColor
maskLayer.path = path;
maskLayer.fillRule = kCAFillRuleEvenOdd
// Release the path since it's not covered by ARC.
overlayView.layer.mask = maskLayer
overlayView.clipsToBounds = true
return overlayView
}
The above solution works great.
Say if you are looking for mask with rectangle area here is the snippet below
let fWidth = self.frame.size.width
let fHeight = self.frame.size.height
let squareWidth = fWidth/2
let topLeft = CGPoint(x: fWidth/2-squareWidth/2, y: fHeight/2-squareWidth/2)
let topRight = CGPoint(x: fWidth/2+squareWidth/2, y: fHeight/2-squareWidth/2)
let bottomLeft = CGPoint(x: fWidth/2-squareWidth/2, y: fHeight/2+squareWidth/2)
let bottomRight = CGPoint(x: fWidth/2+squareWidth/2, y: fHeight/2+squareWidth/2)
let cornerWidth = squareWidth/4
// Step 2
let path = CGMutablePath()
path.addRoundedRect(in: CGRect(x: topLeft.x, y: topLeft.y,
width: topRight.x - topLeft.x, height: bottomLeft.y - topLeft.y),
cornerWidth: 20, cornerHeight: 20)
path.addRect(CGRect(origin: .zero, size: self.frame.size))
// Step 3
let maskLayer = CAShapeLayer()
maskLayer.backgroundColor = UIColor.clear.cgColor
maskLayer.path = path
// For Swift 4.0
maskLayer.fillRule = kCAFillRuleEvenOdd
// For Swift 4.2
//maskLayer.fillRule = .evenOdd
// Step 4
self.layer.mask = maskLayer
self.clipsToBounds = true
rectangle mask looks like this

Resources