最初知道這個屬性還是在iOS核心動畫高級技巧/視覺效果/圖層蒙版看到的,然后隨著對mask屬性的了解,以及一些炫酷動畫分析,原來很多炫酷的動畫其實現原理竟那樣簡單。
現在回想以前看到的Twitter啟動動畫
,我就呵呵一笑,其中就是用了CALayer的mask屬性,它也是一個CALayer,所以就需要創建一個CALayer作為mask:
let maskLayer=CALayer()
maskLayer.contents=UIImage(named: "social-twitter-outline")?.CGImage
maskLayer.position=navigationController.view.center
maskLayer.bounds=CGRectMake(0, 0, 60, 60)
navigationController.view.layer.mask=maskLayer
此時,效果如圖:
twitter
然后給mask添加動畫,先縮小一點,然后逐漸放大:
//add animation
let twitterMaskAnimation:CAKeyframeAnimation=CAKeyframeAnimation(keyPath: "bounds")
twitterMaskAnimation.duration=1.0
twitterMaskAnimation.beginTime=CACurrentMediaTime()+1.0;//delay for a second
let initalBounds=NSValue(CGRect:maskLayer.bounds)
let secondBounds=NSValue(CGRect:CGRectMake(0, 0, 50, 50))//reduce some size
let finalBounds=NSValue(CGRect: CGRectMake(0, 0, 2000, 2000))
twitterMaskAnimation.values = [initalBounds,secondBounds,finalBounds]
twitterMaskAnimation.keyTimes=[0,0.5,1]
twitterMaskAnimation.timingFunctions=[CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut),CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut),CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)]
twitterMaskAnimation.removedOnCompletion=false
twitterMaskAnimation.fillMode=kCAFillModeForwards
navigationController.view.layer.mask?.addAnimation(twitterMaskAnimation, forKey: "twitterMaskAnimation")
此時的動畫效果如下圖:
twitter animation
效果出來了有木有.
當然其中還有些效果不怎么好,在navigation.view和mask之間添加一個白色的背景,這樣看起來會有一個非常好的過渡:
//add a maskBackgroundView with whiteColor
let maskBackgroudView:UIView=UIView.init(frame: navigationController.view.bounds)
maskBackgroudView.backgroundColor=UIColor.whiteColor()
navigationController.view.addSubview(maskBackgroudView)
navigationController.view.bringSubviewToFront(maskBackgroudView)
最后還需要添加一些其他的動畫,maskBackgroundView逐漸消失以及給navigationController.view添加bounce的動畫,看起來更加和諧一些:
//maskBackgroudView fade animation
UIView.animateWithDuration(0.1, delay: 1.35, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in
maskBackgroudView.alpha=0
}) { (finished:Bool) -> Void in
maskBackgroudView.removeFromSuperview()
}
//navigationController.view bounce animation
UIView.animateWithDuration(0.25, delay: 1.3, options: UIViewAnimationOptions.TransitionNone, animations: { () -> Void in
navigationController.view.transform=CGAffineTransformMakeScale(1.05, 1.05)
}) { (finished:Bool) -> Void in
UIView.animateWithDuration(0.3, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in
navigationController.view.transform = CGAffineTransformIdentity
}, completion: { (finished:Bool) -> Void in
navigationController.view.layer.mask=nil
})
}
實現最終效果如圖:
twitter splash