效果图
项目地址:ImageMaskTransition
转场原理
对于模态展示(Modal)
iOS 8之后,可以通过设置ViewController的转场代理
transitioningDelegate
这个转场代理是一个协议类型UIViewControllerTransitioningDelegate
.由于我们是非交互式转场,所以只需要实现协议的两个方法即可
// MARK: - UIViewControllerTransitioningDelegate -
func animationControllerForPresentedController(presented: UIViewController,presentingController presenting: UIViewController,sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
//这里返回present的动画
}
func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
//这里返回dismiss的动
}
对于NavigationController来说,则可以设置NavigationController的delegate来返回自定义的动画。
navigationController.delegate
这里的delegate
是UINavigationControllerDelegate
类型,在不考虑交互式转场的情况下,我们只需要实现以下方法即可
//返回动画
func navigationController(navigationController: UINavigationController,animationControllerForOperation operation: UINavigationControllerOperation,fromViewController fromVC: UIViewController,toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
switch operation {
case .Pop:
//返回Pop时候
case .Push:
//返回Push时候的动画
default:
return nil
}
}
细心的朋友应该发现了,不管是模态还是Push,都是返回一个UIViewControllerAnimatedTransitioning
协议类型的对象
通用的Animator
定义一个类,让其遵循UIViewControllerAnimatedTransitioning
协议,来实现实际的动画,
class ImageMaskAnimator: NSObject,UIViewControllerAnimatedTransitioning {}
由于实现了UIViewControllerAnimatedTransitioning
协议,所以要提供两个方法
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
//这里返回动画的时间
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
//这里进行实际的动画
}
转场的原理
在上文提到的transitionDuration
方法中,可以看到有一个参数是transitionContext
,这个是转场上下文。通过转场上下文,可以获得fromView
,toView
以及containView
,
let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)!
let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!
let containView = transitionContext.containerView()!
其中,关系如图
所以,开发者要做的就是
- 把toView添加到转场ContainView中,并且定义好toView的初始位和状态
- 定义好FromView和ToView的转场结束时候的状态
- 创建fromView到toView动画
用CIFilter截图并添加高斯模糊
细心的朋友能看到,在最上面转场的时候,不管是present还是dismiss,第一个Controller的看起来都是”模糊”的。其实是采用截图,然后添加一个ImageView
覆盖到转场的ContainView上
实现的效果。其中,截图,并添加模糊的代码如下
extension UIView{
func blurScreenShot(blurRadius:CGFloat)->UIImage?{
guard self.superview != nil else{
return nil
}
UIGraphicsBeginImageContextWithOptions(CGSize(width: frame.width,height: frame.height),false,1)
layer.renderInContext(UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext();
guard let blur = CIFilter(name: "CIGaussianBlur") else{
return nil
}
blur.setValue(CIImage(image: image),forKey: kCIInputImageKey)
blur.setValue(blurRadius,forKey: kCIInputRadiusKey)
let ciContext = CIContext(options: nil)
let result = blur.valueForKey(kCIoUtputImageKey) as! CIImage!
let boundingRect = CGRect(x:0,y: 0,width: frame.width,height: frame.height)
let cgImage = ciContext.createCGImage(result,fromRect: boundingRect)
let filteredImage = UIImage(CGImage: cgImage)
return filteredImage
}
}
Tips:在模拟器上,CIFilter的效率很差,但是真机上很快
Present/Push动画过程
首先,我们要做一些准备工作,其中,核心是坐标系转换
Tips:
Swift通过以下代码块来实现条件编译,可以通过条件编译来适配多版本Swift
#if
//...
#else
..
#endif
整个动画的准备过程
//获取必要参数
let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)!
let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!
let containView = transitionContext.containerView()!
let frame = UIScreen.mainScreen().bounds
maskContentView = UIImageView(frame: frame)
maskContentView.backgroundColor = UIColor.lightGrayColor()
//如果是Present或者push
if self.transitionType == .Present {
//模拟器上禁用Blur
#if (arch(i386) || arch(x86_64)) && os(iOS)
print("Wow,CIFilter is too slow on simulator,So I disable blur on Simulator")
#else
//截图,生成blur
self.blurImage = fromView.blurScreenShot(3.0)
maskContentView.image = fromView.blurScreenShot(3.0)
#endif
//Blur作为背景,添加到ContainView
maskContentView.frame = containView.bounds
containView.addSubview(self.maskContentView)
let fromImageView = self.config.fromImageView
//Frame的坐标系适配
let adjustFromRect = fromImageView.convertRect(fromImageView.bounds,toView: containView)
let toImageView = self.config.toImageView!
let adjustToRect = toImageView.convertRect(toImageView.bounds,toView: containView)
//添加一个ImageView,来显示动画
imageView = UIImageView(frame: adjustFromRect)
imageView.image = fromImageView.image
containView.addSubview(imageView)
//设置阴影
imageView.layer.shadowColor = UIColor.blackColor().CGColor
imageView.layer.shadowOffset = CGSizeMake(2.0,2.0)
imageView.layer.shadowRadius = 10.0
imageView.layer.shadowOpacity = 0.8
//开始动画
//动画代码....
到这里,视图的层次结构如下
- ContainView
- fromView
- maskContentView
- imageView
整个Present的动画分为三个部分
//第一步,移动ImageView到toView的对应Frame,同时变化Scale
UIView.animateWithDuration(0.5 / 1.6 * self.config.presentDuration,animations: {
self.imageView.frame = adjustToRect
self.imageView.transform = CGAffineTransformMakeScale(1.2,1.2)
}) { (finished) in
//第二步,恢复ImageView的Transfrom
UIView.animateWithDuration(0.3 / 1.6 * self.config.presentDuration,animations: {
self.imageView.transform = CGAffineTransformIdentity
self.imageView.layer.shadowOpacity = 0.0
}) { (finished) in
//第三步,添加toView,然后开始mask动画
containView.addSubview(toView)
containView.bringSubviewToFront(self.imageView)
let adjustFrame = self.imageView.convertRect(self.imageView.bounds,toView: self.maskContentView)
toView.maskFrom(adjustFrame,duration: 0.8 / 1.6 * self.config.presentDuration,complete: {
//所有动画完成,进行清理
self.maskContentView.removeFromSuperview()
self.imageView.removeFromSuperview()
self.maskContentView = nil
self.imageView = nil
//通知上下文,转场完成
transitionContext.completeTransition(true)
})
}
}
在最后一步进行Mask的时候,视图的层次如下
- ContainView
- fromView
- maskContentView
- toView
- imageView
Mask动画
Mask动画其实比较简单,我们都知道CALayer有一个mask
属性,它也是一个CALayer,整个Mask动画的过程如下
- 用CAShapeLayer作为对应View的
mask
- 通过动画CAShapeLayer的
path
属性-实现一个逐渐扩大的圆来实现对应的mask动画
代码如下
maskLayer.path = toPath.CGPath
let basicAnimation = CABasicAnimation(keyPath: "path")
basicAnimation.duration = duration
basicAnimation.fromValue = fromPath.CGPath
basicAnimation.toValue = toPath.CGPath
basicAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaSEOut)
maskLayer.addAnimation(basicAnimation,forKey: "pathMask")
self.layer.mask = maskLayer
其中,fromPath是开始的圆环,toPath是结束的圆环。
圆环的绘制采用贝赛尔曲线
let fromPath = UIBezierPath(arcCenter: fromCenter,radius: fromRadius,startAngle: 0,endAngle: CGFloat(M_PI) * 2,clockwise: true)
事务
这里用事务进行包裹,进而在动画完成的时候进行反馈
CATransaction.begin()
CATransaction.setCompletionBlock {
//这里动画完成了
}
//上文的Mask代码
CATransaction.commit()
Dismiss/Pop的原理类似,不再赘述
最后
完整代码地址:ImageMaskTransition
欢迎Follow我的Github,LeoMobileDeveloper