需求
我需要做一个mask中空遮罩,也就是遮罩的内部空出一个巨型区域,中空的矩形区域需要动画地变化
中空遮罩的实现
let emptyRect = CGRect(x: originx, y: originy, width: w, height: h)
let path1 = UIBezierPath(rect: myView.bounds)
let path2 = UIBezierPath(rect: emptyRect)
path1.append(path2.reversing())
maskLayer.path = path1
myView.layer.mask = maskLayer
path带动画变化
let newEmptyRect = CGRect(x: originx1, y: originy1, width: w1, height: h1)
let path1 = UIBezierPath(rect: myView.bounds)
let path2 = UIBezierPath(rect: newEmptyRect)
path1.append(path2.reversing())
maskLayer.path = path1
myView.layer.mask = maskLayer
let ani = CABasicAnimation(keyPath: "path")
ani.fromValue = maskLayer.path
ani.toValue = path1.cgPath
ani.duration = 0.2
ani.repeatCount = 1
ani.fillMode = .forwards
ani.isRemovedOnCompletion = false
maskLayer.add(ani, forKey: nil)
CATransaction.begin()
CATransaction.setDisableActions(true)
maskLayer.path = path1.cgPath
CATransaction.commit()
如果不加后面的CATransaction,动画是不会生效的