为什么当我在 iOS 上设置 window 背景颜色时,遮罩的背景颜色会发生变化?

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

我做一个 Twitter 动画项目作为练习。我想改变遮罩的背景颜色,但我不知道为什么要设置window背景颜色来改变它。

这是我在 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
}

你也可以为掩码设置 backgroundcolor 但它不是 UIColor,它应该是 CGColor 之类的,

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

您正在遮盖添加遮罩的视图。 I.o.w。您正在屏蔽 self.window?.rootViewController?.view.

蒙版,通过使用它所应用到的图层的 Alpha 通道,像模板一样剪切区域。因此,根据您应用的掩码,self.window?.rootViewController?.view 将是 'cut'。因为 self.window?.rootViewController?.view 直接在 self.window 之上,所以 self.window 将在切出的部分可见。如果未设置 backgroundColor,您将看到黑色背景,这是 Window 的默认背景色。我希望这是有道理的。