iOS-Swift4.1环形进度指示器+图片加载动画

demo.gif

如图,这个动画的是如何做的呢?

分析:

  • 1.环形进度指示器,根据下载进度来更新它
  • 2.扩展环,向内向外扩展这个环,中间扩展的时候,去掉这个遮盖

一.环形进度指示器

1.自定义View继承UIView,命名为CircularLoaderView.swift,此View将用来保存动画的代码

2.创建CAShapeLayer

let circlePathLayer = CAShapeLayer()
let circleRadius: CGFloat = 20.0

3.初始化CAShapeLayer

// 两个初始化方法都调用configure方法
override init(frame: CGRect) {
    super.init(frame: frame)
    configure()
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder : aDecoder)
    configure()
}


// 初始化代码来配置这个shape layer:
func configure(){
    circlePathLayer.frame = bounds
    circlePathLayer.lineWidth = 2.0
    circlePathLayer.fillColor = UIColor.clear.cgColor
    circlePathLayer.strokeColor = UIColor.red.cgColor
    layer.addSublayer(circlePathLayer)
    backgroundColor = .white
    progress = 0.0
}

4.设置环形进度条的矩形frame

// 小矩形的frame
func circleFrame() -> CGRect {
    
    var circleFrame = CGRect(x: 0, y: 0, width: 2*circleRadius, height: 2*circleRadius)
    let circlePathBounds = circlePathLayer.bounds
    circleFrame.origin.x = circlePathBounds.midX - circleFrame.midX
    circleFrame.origin.y = circlePathBounds.midY - circleFrame.midY
    return circleFrame
}

可以参考下图,理解这个circleFrame

Snip20160705_3.png

5.每次自定义的这个view的size改变时,你都需要重新计算circleFrame,所以要将它放在一个独立的方法,方便调用

// 通过一个矩形(正方形)绘制椭圆(圆形)路径
func circlePath() -> UIBezierPath {
    return UIBezierPath.init(ovalIn: circleFrame())
}

6.由于layers没有autoresizingMask这个属性,你需要在layoutSubviews方法中更新circlePathLayerrame来恰当地响应viewsize变化

override func layoutSubviews() {
    super.layoutSubviews()
    
    circlePathLayer.frame = bounds
    circlePathLayer.path = circlePath().cgPath
}

7.给CircularLoaderView.swift文件添加一个CGFloat类型属性,自定义的settergetter方法,setter方法验证输入值要在0到1之间,然后赋值给layerstrokeEnd属性。

var progress : CGFloat{
    get{
        return circlePathLayer.strokeEnd
    }
    
    set{
        if (newValue > 1) {
            circlePathLayer.strokeEnd = 1
        }else if(newValue < 0){
            circlePathLayer.strokeEnd = 0
        }else{
            circlePathLayer.strokeEnd = newValue
        }
    }
}

8.利用Kingfisher,在image下载回调方法中更新progress.
此处是自定义ImageView,在storyboard中拖个ImageView,设置为自定义的ImageView类型,在这个ImageView初始化的时候就会调用下面的代码

class CustomImageView: UIImageView {
    // 创建一个实例对象
    let progressIndicatorView = CircularLoaderView(frame: CGRect.zero)
    
    // 从xib中加载会走这个方法
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
        addSubview(progressIndicatorView)
        progressIndicatorView.frame = bounds
        

        let url = URL.init(string: "https://koenig-media.raywenderlich.com/uploads/2015/02/mac-glasses.jpeg")
        
        self.kf.setImage(with: url, placeholder: nil, options: nil, progressBlock: { [weak self] (reseivdSize, expectedSize) in
            self?.progressIndicatorView.progress = CGFloat(reseivdSize) / CGFloat(expectedSize)
        }) { [weak self] (image, error, _, _) in
            self?.progressIndicatorView.reveal()
        }
    }
}

二.扩展这个环

仔细看,此处是两个动画一起执行,1是向外扩展2.是向内扩展.但可以用一个Bezier path完成此动画,需要用到组动画.

  • 1.增加圆的半径(path属性)来向外扩展
  • 2.同时增加line的宽度(lineWidth属性)来使环更加厚和向内扩展
func reveal() {
    // 背景透明,那么藏着后面的imageView将显示出来
    backgroundColor = .clear
    progress = 1.0
    
    // 移除隐式动画,否则干扰reveal animation
    circlePathLayer.removeAnimation(forKey: "strokenEnd")
    
    // 从它的superLayer 移除circlePathLayer ,然后赋值给super的layer mask
    circlePathLayer.removeFromSuperlayer()
    // 通过这个这个circlePathLayer 的mask hole动画 ,image 逐渐可见
    superview?.layer.mask = circlePathLayer
    
    // 1 求出最终形状
    let center = CGPoint(x:bounds.midX,y: bounds.midY)
    let finalRadius = sqrt((center.x*center.x) + (center.y*center.y))
    let radiusInset = finalRadius - circleRadius
    
    
    let outerRect = circleFrame().insetBy(dx: -radiusInset, dy: -radiusInset)
    // CAShapeLayer mask最终形状
    let toPath = UIBezierPath.init(ovalIn: outerRect).cgPath
    
    
    // 2 初始值
    let fromPath = circlePathLayer.path
    let fromLineWidth = circlePathLayer.lineWidth
    
    // 3 最终值
    CATransaction.begin()
    // 防止动画完成跳回原始值
    CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions)
    circlePathLayer.lineWidth = 2 * finalRadius
    circlePathLayer.path = toPath
    CATransaction.commit()
    
    // 4 路径动画,lineWidth动画
    let lineWidthAnimation = CABasicAnimation(keyPath: "lineWidth")
    lineWidthAnimation.fromValue = fromLineWidth
    lineWidthAnimation.toValue = 2*finalRadius
    let pathAnimation = CABasicAnimation(keyPath: "path")
    pathAnimation.fromValue = fromPath
    pathAnimation.toValue = toPath
    
    // 5 组动画
    let groupAnimation = CAAnimationGroup()
    groupAnimation.duration = 1
    groupAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
    groupAnimation.animations = [pathAnimation ,lineWidthAnimation]
    groupAnimation.delegate = self
    circlePathLayer.add(groupAnimation, forKey: "strokeWidth")
}
photo-loading-diagram.png

三.监听动画的结束

extension CircularLoaderView :CAAnimationDelegate {
    // 移除mask
    func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
        superview?.layer.mask = nil
    }
}

示例下载地址github
原文地址 Rounak Jain
参考地址

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

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 170,569评论 25 707
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 11,614评论 4 59
  • 突然想起来王小坏了,可能是因为太喜欢他了。电脑桌面一直都是他不同时期的个人写真。看起来总是那么顺眼,也许是因为我亲...
    萨迪噶阅读 607评论 0 0
  • 没有动力的生活 有往前一步的想法都是自杀
    Victory99阅读 67评论 0 1
  • 整一天都在下雨,心里也很烦闷,半下午终于在电钻声中爆发了,我想回去,想丢下一切可有可无的东西回去,回到梦里最深沉的...