Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift mask of circle layer over UIView

Tags:

ios

swift

I am attempting to mask a square UIView by a circular CAShapeLayer in swift. I have the following:

    var snapFrame = self.snapButton.frame
    var innerFrame = CGRect(x: snapFrame.minX + 1, y: snapFrame.minY + 1, width: snapFrame.width - 2, height: snapFrame.height - 2)

    maskLayer = CAShapeLayer()
    var circlePath = UIBezierPath(roundedRect: innerFrame, cornerRadius: innerFrame.width)
    maskLayer.path = circlePath.CGPath
    maskLayer.fillColor = UIColor.clearColor().CGColor

    shutterOverlay = UIView()
    shutterOverlay.frame = innerFrame
    shutterOverlay.backgroundColor = BUBConstants.primaryColor_blue

    self.view.addSubview(shutterOverlay)
    self.view.layer.addSublayer(maskLayer)

    shutterOverlay.layer.mask = maskLayer

If I comment out the last two lines, both the layer and the view appear in the correct places and at the correct sizes. However, adding the last line causes both the view and layer to not be shown.

Also, I need to do it this way as my end goal is to have an animation where the square UIView fills up the circle. I can't just show a circular view.

Can anyone point me to where I am going wrong?

like image 240
lbrendanl Avatar asked Mar 20 '15 18:03

lbrendanl


1 Answers

You need to add the mask to the shutterOverlay like this

shutterOverlay.layer.addSublayer(maskLayer)

instead of the view's layer.

The mask needs to be a sublayer of the layer it wants to mask out.

like image 120
Thomas Krajacic Avatar answered Sep 21 '22 02:09

Thomas Krajacic