ovo ovo - 22 days ago 7
Swift Question

Why a mask's background color changes when I set the window background color on iOS?

I do a twitter animation project as practice. I want to change the mask's background color, but I don't know why to set the window background color to change it.

Here is my code in AppDelegate

var mask: CALayer?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

self.mask = CALayer()
self.mask?.contents = UIImage(named: "twitter")?.cgImage
self.mask?.contentsGravity = kCAGravityResizeAspect
self.mask?.bounds = CGRect(x: 0, y: 0, width: 100, height: 100)
self.mask?.position = self.window!.center

self.window?.rootViewController?.view.layer.mask = self.mask
self.window?.backgroundColor = UIColor(red: 18/255, green: 145/255, blue: 242/255, alpha: 1) // Why?

return true
}

Answer

You are masking the view that you add the mask to. I.o.w. You are masking self.window?.rootViewController?.view.

A mask, cuts out the area like a stencil, by using the alpha channels of the layer that it is applied to. Therefor, self.window?.rootViewController?.view, will be 'cut' according to the mask that you apply. Because self.window?.rootViewController?.view is directly on top of self.window, self.window will be visible at the cut out pieces. If the backgroundColor was not set, you will see a black background, which is the default background color for the Window. I hope this make sense.