dcbenji
dcbenji

Reputation: 4678

Mask a View with the alpha from another view in Swift

I've been struggling for a view hours to figure out how to get my view masked by a shape that is in another view. Basically I have a circular countdown timer that I want to be masked out by an animating circle that scales up from the center of the timer when the timer is reset.

I tried setting timerMask.maskView = timerCircleGrahics where timerCircleGraphics is the name of my timer animation view. But this is giving me very strange results when I test the app. It seems to clip the view to the rectangle bounds of my mask view rather than the alpha of the bounds that are drawn within that view. The mask layer is centered and being drawn properly, but I've never attempted this before so am not sure if I am doing it right.

Here is the class for my mask shape:

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 assign this mask to a manually placed View in my Storyboard called timerMask. I am realizeing now that by assigning timerBackgroundMask class to timerMask I have programatically added a subview to my manually placed Storyboard view, but I feel like the alpha should come through just the same when set this view to mask out anotherview. Here is the code i use to set the mask

timerCircleGraphics.layer.mask = timerMask.layer

The result I am getting is pretty weird:

enter image description here

The red portion should be a circle that is partially clipped by my timerMask from the center outward. The light green circle that you see is simply the background view of the counter, however it happens to be the exact position and size as my timerBackgroundMask for reference.

Upvotes: 3

Views: 3206

Answers (1)

Rikkles
Rikkles

Reputation: 3372

Don't bother creating a class and using the Storyboard. Do it straight in code, the 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

Upvotes: 1

Related Questions