如何更改蒙版视图的颜色?

时间:2018-02-01 19:25:39

标签: swift mask

我不确定我是否理解Masking的正确概念,但我试图在他们的应用中重新创建Twitter徽标扩展动画:

Twitter Logo expansion

到目前为止我有这个代码:

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
    }
}

这个输出是:

enter image description here

如何将黑色背景更改为蓝色?我尝试过,但它似乎没有效果:

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

2 个答案:

答案 0 :(得分:1)

创建一个应用蒙版的中间层。将视图的背景设置为所需的背景,并将中间层的背景颜色设置为您希望蒙版出现的颜色。像这样,

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

答案 1 :(得分:0)

这可以通过更改appDelegate窗口的背景颜色来实现...

let appDelegate  = UIApplication.shared.delegate as! AppDelegate
appDelegate.window!.backgroundColor = UIColor.blue