Quick circular layer mask over UIView

I am trying to mask a square UIView with 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 on the last two lines, both the layer and the view will appear in the right places and in the right sizes. However, adding the last line results in the view and layer not being displayed.

In addition, I need to do it this way, since my ultimate goal is animation, where the UIView square fills the circle. I can’t just show a circular view.

Can someone point me where I am wrong?

+6
source share
1 answer

You need to add a mask to shutterOverlay like this

 shutterOverlay.layer.addSublayer(maskLayer) 

instead of the view layer.

The mask should be a sublayer of the layer that it wants to mask.

+9
source

Source: https://habr.com/ru/post/984063/


All Articles