Search code examples
swiftmask

How to change the color of the Mask View?


I am not sure if I understand the concept of Masking correctly but I am trying to recreate the Twitter logo expansion animation in their app:

Twitter Logo expansion

I have this code so far:

class LaunchScreenViewController: UIViewController {
    var mask: CALayer!

    override func viewDidLoad() {
        setUpViewMask()
    }

    func setUpViewMask() {
        mask = CALayer()
        mask.contents = UIImage(named: "logo_mask")?.cgImage
        mask.contentsGravity = kCAGravityResizeAspect
        mask!.bounds = CGRect(x: 0, y: 0, width: 100, height: 100)
        mask!.anchorPoint = CGPoint(x: 0.5, y: 0.5)
        mask!.position = CGPoint(x: view.frame.size.width/2, y: view.frame.size.height/2)
        view.layer.backgroundColor = UIColor(red: 70/255, green: 154/255, blue: 233/255, alpha: 1).cgColor
        view.layer.mask = mask
    }
}

The output of this is:

enter image description here

How would I change the black background to be blue? I tried doing but it didn't seem to work:

view.layer.backgroundColor = UIColor(red: 70/255, green: 154/255, blue: 233/255, alpha: 1).cgColor

Solution

  • Create an intermediate layer where you apply mask. Set the background of your view to the desired background, and set background color of the intermediate layer to the color that you wish your mask to appear in. Something like this,

    view.backgroundColor = UIColor(red: 70/255, green: 154/255, blue: 233/255, alpha: 1)  // set background of the view portion that do not include mask
    
    
    let parentLayer = CALayer()
    parentLayer.frame = view.bounds
    parentLayer.backgroundColor = UIColor.white.cgColor // sets background of mask
    view.layer.addSublayer(parentLayer) 
    
    let mask = CALayer()
    mask.contents = UIImage(named: "twitter.png")?.cgImage
    mask.contentsGravity = kCAGravityResizeAspect
    mask.bounds = CGRect(x: 0, y: 0, width: 100, height: 100)
    mask.anchorPoint = CGPoint(x: 0.5, y: 0.5)
    mask.position = CGPoint(x: view.frame.size.width/2, y: view.frame.size.height/2)
    parentLayer.mask = mask