I have this PNG file, which I'd like to use as a mask for a UIView
.
The view must be:
- 20 pixels/points in from each side
- A perfect square
- Centered vertically
I set the following constraints to accomplish this:
However, it seems these constraints don't play well with masks. When these constraints and the mask
property are set, I get the following:
but I'd like the view to look just like the mask above, except orange (The backgroundColor
here is just for simplicity—I later add subviews that need to be masked.)
However, when no constraints are set, the mask
seems to work properly and I get something like this (borderColor
added for visual purposes only):
Here's my code (viewForLayer
is a UIView I made in the storyboard):
viewForLayer.layer.borderColor = UIColor.redColor().CGColor
viewForLayer.layer.borderWidth = 10
var mask = CALayer()
mask.contents = UIImage(named: "TopBump")!.CGImage
mask.frame = CGRect(x: 0, y: 0, width: viewForLayer.bounds.width, height: viewForLayer.bounds.height)
mask.position = CGPoint(x: viewForLayer.bounds.width/2, y: viewForLayer.bounds.height/2)
viewForLayer.layer.mask = mask
viewForLayer.backgroundColor = UIColor.orangeColor()
The problem is though, that now the view isn't the right size or in the right position—it doesn't follow the rules above—"The view must be: ". How can I have the mask
work properly, and the auto-layout constraints set at the same time?
I found a way around it. Not sure if this is the best way but here we go...
https://i.stack.imgur.com/k1e3N.jpg
Just make sure you change the name of the UIView class in the storyboard inspector too. Apparently, the trick is to set the mask frame for each layoutSubviews call.