【问题标题】:Why a mask's background color changes when I set the window background color on iOS?为什么当我在 iOS 上设置窗口背景颜色时,遮罩的背景颜色会发生变化?
【发布时间】:2016-11-14 07:08:07
【问题描述】:

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

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

【问题讨论】:

    标签: ios swift window calayer mask


    【解决方案1】:

    您正在对添加掩码的视图进行掩码。 I.o.w.你在屏蔽self.window?.rootViewController?.view

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

    【讨论】:

    • 谢谢,我知道了。
    【解决方案2】:

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

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

    【讨论】:

    • 这行不通。蒙版变为正方形,背景仍为黑色。
    猜你喜欢
    • 2018-01-06
    • 2021-02-13
    • 1970-01-01
    • 1970-01-01
    • 2014-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-29
    相关资源
    最近更新 更多