Swift之微信朋友圈图片浏览器

Swift之微信朋友圈图片浏览器

最近闲来无事,突然对微信, 微博, QQ等社交APP的九宫格的图片浏览功能非常感兴趣, 最近就尝试着研究了一下:

这里先附上Demo地址

  • 在介绍项目之前, 先介绍三个基础知识
    • CATransition转场动画
    • ViewController自定义转场
    • UIBesization贝塞尔曲线

一. CATransition转场动画

示例代码

//4. 转场动画
let transition = CATransition()
transition.type = transitionType
transition.subtype = isNext ? kCATransitionFromRight : kCATransitionFromLeft
transition.duration = 1
downloadImage(url: imageURL)
baseImage.layer.add(transition, forKey: "transition")

更多关于该动画的详细介绍, 可参考iOS出门必备之CoreAnimation(核心动画)中第七种CA动画, 故这里不多做介绍

二. ViewController自定义转场

从iOS7开始,苹果更新了自定义ViewController转场的API,会用到的几个协议protocol:

  • 描述ViewController转场的:
    • UIViewControllerTransitioningDelegate
    • UINavigationControllerDelegate
    • UITabBarControllerDelegate
  • 定义动画内容的
    • UIViewControllerAnimatedTransitioning
    • UIViewControllerInteractiveTransitioning
  • 表示动画上下文的
    • UIViewControllerContextTransitioning

1-1. 描述ViewController转场的

  • 为什么苹果要引入这一套API?因为在iOS7之前,做转场动画很麻烦,要写一大堆代码在ViewController中。
  • 引入这一套API之后,在丰富功能的同时极大程度地降低了代码耦合,实现方式就是将之前在ViewController里面的代码通过protocol分离了出来。
  • 顺着这个思路往下想,实现自定义转场动画首先需要找到ViewController的delegate。
  • 苹果告诉我们切换ViewController有三种形式:
    • UITabBarController内部切换
    • UINavigationController切换
    • present ViewController
    • 这三种方式是不是需要不同的protocol呢?

1-2. 详解Protocol

  • UIViewControllerTransitioningDelegate 自定义模态转场动画时使用。

    • 设置UIViewController的属性transitioningDelegate
    weak open var transitioningDelegate: UIViewControllerTransitioningDelegate?
    
  • UINavigationControllerDelegate 自定义navigation转场动画时使用

    • 设置UINavigationController的属性delegate
    weak open var delegate: UINavigationControllerDelegate?
    
  • UITabBarControllerDelegate自定义tab转场动画时使用

    • 设置UITabBarController的属性delegate
    weak open var delegate: UITabBarControllerDelegate?
    

实际上这三个protocol干的事情是一样的只不过他们的应用场景不同罢了。我们下面以UINavigationControllerDelegate为例,其他的类似

  • UINavigationControllerDelegate主要的方法
    @available(iOS 7.0, *)
    optional public func navigationController(_ navigationController: UINavigationController, interactionControllerFor animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning?

    
    @available(iOS 7.0, *)
    optional public func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning?

  • 两个方法分别返回UIViewControllerInteractiveTransitioningUIViewControllerAnimatedTransitioning,它们的任务是描述动画行为(转场动画如何执行,就看它俩的)。
  • 从名字可以看出,这两个protocol的区别在于是否是interactive的。如何理解?
  • interactive动画可以根据输入信息的变化改变动画的进程。例如iOS系统为UINavigationController提供的默认右滑退出手势就是一个interactive 动画,整个动画的进程由用户手指的移动距离控制

1-3. UIViewControllerInteractiveTransitioning协议

定义了两个属性可以做到平滑过渡

  • completionCurve: 交互结束后剩余动画的速率曲线
  • completionSpeed: 交互结束后动画的开始速率由该参数与原来的速率相乘得到,实际上是个缩放参数,这里应该使用单位变化速率(即你要的速率/距离)。
  • 注意:
    • completionSpeed会影响剩余的动画时间,而不是之前设定的转场动画时间剩下的时间;
    • completionSpeed很小时剩余的动画时间可能会被拉伸得很长,所以过滤下较低的速率比较好。
    • 如果不设置两个参数,转场动画将以原来的速率曲线在当前进度的速率继续。
    • 不过从实际使用效果来看,往往不到0.5s的动画时间,基本上看不出什么效果来

1-4. 定义动画内容的UIViewControllerAnimatedTransitioning

  • 必须实现的方法
//返回动画的执行时间
public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval

//处理具体的动画  
public func animateTransition(using transitionContext: UIViewControllerContextTransitioning)

1-5. 表示动画上下文UIViewControllerContextTransitioning

  • UIViewControllerContextTransitioning提供了一系列方法
  • 是唯一一个我们不需要实现的Protocol
  • 下面是一些我们常用的属性和方法:
//转场动画发生在该View中    
public var containerView: UIView { get }

//上报动画执行完毕
public func completeTransition(_ didComplete: Bool)

//根据key返回一个ViewController。我们通过`FromViewControllerKey`找到将被替换掉的VC,通过`ToViewControllerKey`找到将要显示的VC
public func viewController(forKey key: UITransitionContextViewControllerKey) -> UIViewController?

//根据key返回一个view, 我们通过from找到将要消失的view, 根据to找到将要弹出的view
@available(iOS 8.0, *)
public func view(forKey key: UITransitionContextViewKey) -> UIView?

1-5. UIViewControllerTransitioningDelegate自定义模态转场时使用

// 该方法是告诉系统,弹出动画交给谁来处理
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
    isPresent = true
    return self
}

// 该方法是告诉系统,消失动画交给谁来处理
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
    isPresent = false
    return self
}

三. 图片浏览器项目介绍

1. 项目结构Alamofire + MVVM

框架结构
图片浏览器.gif

2. 自定义ViewController的弹出和消失动画

2-1. 自定义ViewController弹出和消失的Protocol

//MARK: 自定义协议
protocol JunBrowsePresentDelefate: NSObjectProtocol {
    /// 1. 提供弹出的imageView
    func imageForPresent(indexPath: IndexPath) -> UIImageView
    
    /// 2. 提供弹出的imageView的frame
    func startImageRectForpresent(indexPath: IndexPath) -> CGRect
    
    /// 3.提供弹出后imageView的frame
    func endImageRectForpresent(indexPath: IndexPath) -> CGRect
}

protocol JunBrowserDismissDelegate {
    /// 1.提供推出的imageView
    func imageViewForDismiss() -> UIImageView
    
    /// 2. 提供推出的indexPath
    func indexPathForDismiss() -> IndexPath
}

2-2. 遵循协议

  • UIViewControllerTransitioningDelegate告诉系统弹出/消失动画的处理页面
  • UIViewControllerAnimatedTransitioning
    • 需要返回动画的执行时间
    • 需要在弹出和消失页面的时候分别执行不同的动画
//MARK: UIViewControllerTransitioningDelegate
extension PhotoBrowseAnimation: UIViewControllerTransitioningDelegate {
    // 该方法是告诉系统,弹出动画交给谁来处理
    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresent = true
        return self
    }

    // 该方法是告诉系统,消失动画交给谁来处理
    func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresent = false
        return self
    }
}


//MARK: 继承AnimatedTransitioning协议
extension PhotoBrowseAnimation: UIViewControllerAnimatedTransitioning {
    //返回动画的执行时间
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 0.6
    }
    
    //处理具体的动画
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        isPresent ? presentAnimation(transitionContext) : dismissAnimation(transitionContext)
    }
}

2-3. 图片列表界面

1. 在点击需要展示的imageView的时候,调用下面的方法

// MARK:- 弹出照片浏览器
extension JunScrollViewController {
    fileprivate func presentPhotoBrowse(indexPath: IndexPath) {
        //1. 创建图片浏览器
        let photoBrowseVC = BrowseViewController(images: imageVM.imageArray, currentIndexP: indexPath)
        //2. 设置弹出样式为自定义
        photoBrowseVC.modalPresentationStyle = .custom
        //3. 设置转场动画代理
        photoBrowseVC.transitioningDelegate = photoAnimation
        //4. 设置broseAnimation的属性
        photoAnimation.setProperty(indexPath: indexPath, self, photoBrowseVC)
        //5. 弹出图片浏览器
        present(photoBrowseVC, animated: true, completion: nil)
    }
}

2. 遵循并实现自定义的协议方法

//MARK: JunBrowsePresentDelefate
extension JunScrollViewController: JunBrowsePresentDelefate {
    func imageForPresent(indexPath: IndexPath) -> UIImageView {
        let imageV = UIImageView()
        imageV.contentMode = .scaleAspectFill
        imageV.clipsToBounds = true
        //设置图片
        imageV.kf.setImage(with: URL(string: imageVM.imageArray[indexPath.item].pic74), placeholder: UIImage(named: "coderJun"))
        return imageV
    }
    
    func startImageRectForpresent(indexPath: IndexPath) -> CGRect {
        // 1.取出cell
        guard let cell = imageCollection.cellForItem(at: indexPath) else {
            return CGRect(x: imageCollection.bounds.width * 0.5, y: kScreenHeight + 50, width: 0, height: 0)
        }
        
        // 2.计算转化为UIWindow上时的frame
        return imageCollection.convert( cell.frame, to: UIApplication.shared.keyWindow)
    }
    
    func endImageRectForpresent(indexPath: IndexPath) -> CGRect {
        //1. 取出对应的image的url
        let imageUrl = URL(string: imageVM.imageArray[indexPath.item].pic74)!
        
        //2.从缓存中取出image
        var image = KingfisherManager.shared.cache.retrieveImageInDiskCache(forKey: imageUrl.absoluteString)
        if image == nil {
            image = UIImage(named: "coderJun")
        }
        
        // 3.根据image计算位置
        let imageH = kScreenWidth / image!.size.width * image!.size.height
        let y: CGFloat = imageH < kScreenHeight ? (kScreenHeight - imageH) / 2 : 0
        
        return CGRect(x: 0, y: y, width: kScreenWidth, height: imageH)
    }
}

2-4. 在图片展示界面

  • 遵循并实现相关dismiss协议方法
  • 该协议主要实现viewController返回到该图片对应的IndexPath所在的位置
//MARK: JunBrowserDismissDelegate
extension JunTranstionPhotoController: JunBrowserDismissDelegate{
    func imageViewForDismiss() -> UIImageView {
        let imageV = UIImageView()
        imageV.contentMode = .scaleAspectFill
        imageV.clipsToBounds = true
        
        //设置图片
        imageV.image = baseImage.image
        imageV.frame = baseImage.convert(baseImage.frame, to: UIApplication.shared.keyWindow)
        
        return imageV
    }
    
    func indexPathForDismiss() -> IndexPath {
        return IndexPath(item: currentIndex, section: 0)
    }
}


GitHubDemo地址

  • 注意:
  • 这里只是列出了主要的核心代码,具体的代码逻辑请参考demo
  • 文中相关介绍有的地方如果有不是很详细或者有更好建议的,欢迎联系小编
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 196,099评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,473评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 143,229评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,570评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,427评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,335评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,737评论 3 386
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,392评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,693评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,730评论 2 312
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,512评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,349评论 3 314
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,750评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,017评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,290评论 1 251
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,706评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,904评论 2 335

推荐阅读更多精彩内容