详细分析frame、bounds、center、position、anchorPoint
iOS开发系列--让你的应用“动”起来
老司机带你走进Core Animation 之CAAnimation
iOS CoreAnimation 隐式动画
class ViewController: UIViewController {
var cv: CusView!
var bgLayer: CALayer!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let btn = UIButton(frame: CGRect(x: 50, y: 100, width: 200, height: 50 ))
cv = CusView(frame: CGRect(x: 50 , y: btn.frame.maxY+20, width: 200, height: 200))
cv.backgroundColor = .green
self.view.addSubview(cv)
bgLayer = CALayer()
bgLayer.frame = cv.bounds
cv.layer.addSublayer(bgLayer)
btn.setTitle("changeColor", for: .normal)
btn.backgroundColor = UIColor.gray
view.addSubview(btn)
btn.addTarget(self, action: #selector(clicked), for: .touchUpInside)
}
@objc func clicked(sender: UIButton) {
case3()
}
func case1() {
//CATransaction 只对layer生效,view无效
CATransaction.begin()
// CATransaction.setDisableActions(true)
CATransaction.setAnimationDuration(10)
cv.layer.backgroundColor = UIColor.red.cgColor
CATransaction.commit()
CATransaction.setCompletionBlock {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+3) {
self.cv.layer.backgroundColor = UIColor.green.cgColor
}
}
}
func case2() {
//CATransaction 只对layer生效,view无效
CATransaction.begin()
// CATransaction.setDisableActions(true)
CATransaction.setAnimationDuration(10)
bgLayer.backgroundColor = UIColor.red.cgColor
CATransaction.commit()
CATransaction.setCompletionBlock {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+3) {
self.bgLayer.backgroundColor = UIColor.green.cgColor
}
}
}
func case3() {
let ani = CABasicAnimation(keyPath: "backgroundColor")
ani.duration = 3
ani.toValue = UIColor.red.cgColor
ani.timeOffset = 3
ani.isRemovedOnCompletion = false
ani.fillMode = CAMediaTimingFillMode.forwards
cv.layer.add(ani, forKey: "colorAnimate")
}
}
class CusView: UIView,CAAction {
func run(forKey event: String, object anObject: Any, arguments dict: [AnyHashable : Any]?) {
print("event:\(event) object:\(anObject) dict:\(dict)")
let temp: CALayer? = anObject as? CALayer
guard let layer = temp else { return }
if event == "position" && layer.position == CGPoint(x: 150,y: 270) {
let ca = CABasicAnimation(keyPath: "position")
ca.duration = 3
ca.toValue = CGPoint(x: self.superview?.bounds.width ?? 0/2, y: self.superview?.bounds.height ?? 0/2)
ca.fillMode = CAMediaTimingFillMode.forwards
ca.isRemovedOnCompletion = false
self.layer.add(ca, forKey: "move")
}
}
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
override func action(for layer: CALayer, forKey event: String) -> CAAction? {
let action = super.action(for: layer, forKey: event)
// print("key:\(event)")
return action
}
}
case1通过CATransaction 显示调用提交动画并没有生效(把v.layer.backgroundColor换成cv.backgroundColor)和case2却生效了,why???
通过customview override func action(for layer: CALayer, forKey event: String) -> CAAction? 断点,可以发现无论是修改view本身还是view持有的layer 都会走这个方法,并且返回了一个action为nil,so,并不会产生动画特效,UIview本身禁用了隐式动画的原因也是这个。UIView动画可以通过open class func animate(withDuration duration: TimeInterval, animations: @escaping () -> Void, completion: ((Bool) -> Void)? = nil)类似系统api去实现。也可以在这个接口的动画block里面和外面调用 action(for layer:CALayer ,forKey:String)看看得到的CAAction是否为nil。
而case2 是一个自定义的layer添加到view的layer上,这个自定义layer并没有把自己的CALayerDelegate交给任何对象,so,这个layer执行可以动画的属性时候不会走override func action(for layer: CALayer, forKey event: String) -> CAAction? 这个代理方法,而是去CALayer的Actions或者style字典搜索,然后去调用open class func defaultAction(forKey event: String) -> CAAction?,上面是一层层递进的如果返回结果为NSNull或者nil就会到下一步,如果最后一步仍返回nil,则无动画效果。
前面两个case,虽然我们通过代码去介入了,但具体动画怎么执行的还是有系统完成的,这种动画叫隐式动画,而case3是通过代码的方式添加具体动画行为,这种方式叫显示动画
如图中CAAnimation通过其子类添加动画的方式都是显示动画,这个图还差了一个CAAction协议,具体百度吧
前面提到了UIView是禁止隐式动画的,但是某些系统接口本身就带有动画特效,比如UITableView 的 reloadDate或者open func reloadRows(at indexPaths: [IndexPath], with animation: UITableView.RowAnimation),如果想取消动画效果怎么办?可通过另外一个接口解决问题UIView.performWithoutAnimation { }
另外在CusView中遵循了CAAction代理并实现了其代理方法,这个是为了测试给UIView被禁用的隐式动画属性添加动画行为,也就是实现CAAction去添加动画,再把这个CAAction实例交给CALayerDelegate 的这个接口*/
override func action(for layer: CALayer, forKey event: String) -> CAAction?具体我怎么搞,我也没搞好,哈哈,一般不用搞这么麻烦,直接操作layer就行了,这里只是为了了解这个动画执行的过程
再补充一点:CATransaction这个提交动画的事务会在runloop中自动创建,在runloop即将休眠前(kCFRunLoopBeforeWaiting)调用,是通过栈的形式管理。所以也会导致代码或者说属性已经改变了,但动画还没有执行这种时间差。