Mask a View with alpha from another view in Swift

I have been fighting for hours of browsing to figure out how to get my view to mask out with a shape that is in a different view. Basically I have a circular countdown timer that I want to mask with an animated circle that scales from the center of the timer when the timer is reset.

I tried to set timerMask.maskView = timerCircleGrahics

where timerCircleGraphics

is the name of my timer animation view. But it gives me very strange results when I test my application. It seems to have anchored the view to the rectangle borders of my mask view, not to the alphas of the borders that are drawn inside that view. The mask layer is centered and drawn correctly, but I've never done this so I'm not sure if I'm doing it right.

Here is the class for my mask:

class timerBackgroundMask: UIView {
    override func drawRect(rect: CGRect) {
        var ovalPath = UIBezierPath(ovalInRect: CGRectMake(0, 0, 238, 238))
        colorGreen.setFill()
        ovalPath.fill()
    }
}

      

Then, using IB, I manually assign this mask to a hosted view in my storyboard titled timerMask

. Now I understand that by assigning the class timerBackgroundMask

to timerMask

I have programmed to add a subview to my manual Storyboard view, but I feel like the alpha should go exactly the same when that view masks another view. Here is the code I am using to set the mask

timerCircleGraphics.layer.mask = timerMask.layer

      

The result I am getting is rather strange:

enter image description here

The red part should be a circle partially clipped by mine timerMask

from the center outward. The light green circle you see just represents the background view of the counter, however for reference this is the exact location and size as mine timerBackgroundMask

.

+3


source to share


1 answer


Don't worry about creating a class and using a storyboard. Do it right in your code, in a simple way:



var ovalPath = UIBezierPath(ovalInRect: CGRectMake(0, 0, 238, 238))
colorGreen.setFill()
ovalPath.fill()
var mask = CAShapeLayer()
mask.path = ovalPath.CGPath
timerCircleGraphics.layer.mask = mask

      

+1


source







All Articles