MG--Swift遮照HUD 2

MG--Swift遮照HUD 2

比如网络请求IO读写操作这个操作往往比较耗时这个时候我们往往不需要用户操作这个时候我们就应该提供一个蒙版遮照来防止用户操作就需要用到下面的方法了下面是写的蒙版提示界面我们一般每写的一个界面度会涉及到网络APi请求所以需要HUD


2种遮照效果

image

image

代码实现如下

//
//  MGSquaresAnimationView.swift
//  MGSDKDemo
//  Created by LYM-mg on 2021/1/27.
//  Copyright © 2021 LYM-mg. All rights reserved.
//

import UIKit

public enum MGSquaresAnimationViewType {
    case Square(animationLayerTintColor: UIColor, squareSize: CGFloat)
    case Circle(ballWidth: CGFloat)
}

public class MGSquaresAnimationView: UIView {
    convenience init(frame: CGRect = UIScreen.main.bounds, animationViewType: MGSquaresAnimationViewType = .Circle(ballWidth: 13)) {
        self.init(frame: frame)
        switch animationViewType {
            case .Circle(let ballWidth):
                self._ballWidth = ballWidth
                self.initBallView()
                break
            case .Square(let animationLayerTintColor, let squareSize):
                self.initSquareView()
                self.animationLayer.frame = self.bounds
                self.animationLayerTintColor = animationLayerTintColor
                self.squareSize = squareSize
                
                self.setupAnimation()
                
                let tintColorRef = animationLayerTintColor.cgColor
                animationLayer.backgroundColor = tintColorRef
                break
        }
        self.animationViewType = animationViewType
    }
    
    public override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit {
        print("\(self)--deinit")
    }
    
    // MARK: - Square
    fileprivate var animationLayer: CALayer = CALayer()
    fileprivate var isAnimating: Bool = false
    fileprivate var animationLayerTintColor: UIColor = .white {
        didSet {
            let tintColorRef = animationLayerTintColor.cgColor
            for subLayer in animationLayer.sublayers ?? [] {
                subLayer.backgroundColor = tintColorRef
                if subLayer is CAShapeLayer {

                    let shapeLayer = CAShapeLayer()
                    shapeLayer.strokeColor = tintColorRef
                    shapeLayer.fillColor = tintColorRef
                }
            }
        }
    }
    
    fileprivate var squareSize: CGFloat = 60 {
        didSet {
            self.setupAnimation()
        }
    }
    
    fileprivate var animationViewType: MGSquaresAnimationViewType = .Circle(ballWidth: 13)
    
    func initSquareView() {
//        isUserInteractionEnabled = false
        isHidden = false
        layer.addSublayer(animationLayer)
    }
    
    func startAnimating() {
        switch animationViewType {
            case .Circle(_):
                startPathAnimation()
                break
            case .Square(_ , _):
                if (animationLayer.sublayers != nil) {
                    setupAnimation()
                }
                isHidden = false
                animationLayer.speed = 1.0
                break
        }
       isAnimating = true
    }

    func stopAnimating() {
        switch animationViewType {
            case .Circle(_):
                 ball1.layer.removeAllAnimations()
                 ball1.removeFromSuperview()
                 ball2.layer.removeAllAnimations()
                 ball2.removeFromSuperview()
                 ball3.layer.removeAllAnimations()
                 ball3.removeFromSuperview()
            case .Square(animationLayerTintColor , squareSize):
                animationLayer.speed = 0.0
                isHidden = true
            default:
                break
        }
        isAnimating = false
    }
    
    func setupAnimation() {

        animationLayer.sublayers = nil

        setupAnimation(layer: animationLayer, with: CGSize(width: self.squareSize, height: self.squareSize), tintColor: self.animationLayerTintColor)
        animationLayer.speed = 0.0
    }
    
    func setupAnimation(layer: CALayer, with size: CGSize, tintColor: UIColor) {
        let beginTime = TimeInterval(CACurrentMediaTime())

        let squareSize = floor(size.width / 4.0)

        let oX: CGFloat = (layer.bounds.size.width - size.width) / 2.0
        let oY: CGFloat = (layer.bounds.size.height - size.height) / 2.0
        let colors = [
            UIColor(red: 0.880, green: 0.409, blue: 0.195, alpha: 1),
            UIColor(red: 0.137, green: 0.412, blue: 0.663, alpha: 1),
            UIColor(red: 0.810, green: 0.709, blue: 0.115, alpha: 1),
            UIColor(red: 0.537, green: 0.492, blue: 0.363, alpha: 1)
        ]
        
        for i in 0..<5 {
            let square = CALayer()
            square.frame = CGRect(x: oX, y: oY, width: squareSize, height: squareSize)
            square.anchorPoint = CGPoint(x: 0.5, y: 0.5)
            square.backgroundColor = colors[i].cgColor
            square.shouldRasterize = true
            square.rasterizationScale = UIScreen.main.scale

            let transformAnimation = createKeyframeAnimation(withKeyPath: "transform")
            transformAnimation.duration = 1.6
            transformAnimation.beginTime = beginTime - (Double(i) * (transformAnimation.duration) / 4.0)
            transformAnimation.repeatCount = MAXFLOAT

            transformAnimation.keyTimes = [NSNumber(value: 0.0), NSNumber(value: 0.25), NSNumber(value: 0.50), NSNumber(value: 0.75), NSNumber(value: 1.0)]
            
            transformAnimation.timingFunctions = [
                CAMediaTimingFunction(name: .easeInEaseOut),
                CAMediaTimingFunction(name: .easeInEaseOut),
                CAMediaTimingFunction(name: .easeInEaseOut),
                CAMediaTimingFunction(name: .easeInEaseOut),
                CAMediaTimingFunction(name: .easeInEaseOut)
            ]
            
            var t1 = CATransform3DMakeTranslation(size.width - squareSize, 0.0, 0.0)
            t1 = CATransform3DRotate(t1, degreesToRadians(-90.0), 0.0, 0.0, 1.0)
            t1 = CATransform3DScale(t1, 0.7, 0.7, 1.0)

            var t2 = CATransform3DMakeTranslation(size.width - squareSize, size.height - squareSize, 0.0)
            t2 = CATransform3DRotate(t2, degreesToRadians(-180.0), 0.0, 0.0, 1.0)
            t2 = CATransform3DScale(t2, 1.0, 1.0, 1.0)

            var t3 = CATransform3DMakeTranslation(0.0, size.height - squareSize, 0.0)
            t3 = CATransform3DRotate(t3, degreesToRadians(-270.0), 0.0, 0.0, 1.0)
            t3 = CATransform3DScale(t3, 0.7, 0.7, 1.0)

            var t4 = CATransform3DMakeTranslation(0.0, 0.0, 0.0)
            t4 = CATransform3DRotate(t4, degreesToRadians(-360.0), 0.0, 0.0, 1.0)
            t4 = CATransform3DScale(t4, 1.0, 1.0, 1.0)
            
            transformAnimation.values = [
                NSValue(caTransform3D: CATransform3DIdentity),
                NSValue(caTransform3D: t1),
                NSValue(caTransform3D: t2),
                NSValue(caTransform3D: t3),
                NSValue(caTransform3D: t4)
            ]

            layer.addSublayer(square)
            square.add(transformAnimation, forKey: "animation")
        }
    }
    
    private func degreesToRadians(_ degrees: Double) -> CGFloat {
        return CGFloat((degrees) / 180.0 * Double.pi)
    }
    
    private func createAnimationGroup() -> CAAnimationGroup {
        let animationGroup = CAAnimationGroup()
        animationGroup.isRemovedOnCompletion = false
        return animationGroup
    }
    
    private func createBasicAnimation(withKeyPath keyPath: String?) -> CABasicAnimation {
        let animation = CABasicAnimation(keyPath: keyPath)
        animation.isRemovedOnCompletion = false
        return animation
    }

    private func createKeyframeAnimation(withKeyPath keyPath: String?) -> CAKeyframeAnimation {
        let animation = CAKeyframeAnimation(keyPath: keyPath)
        animation.isRemovedOnCompletion = false
        return animation
    }
    
    
    // MARK: - Circle
    var ball1: UIView = UIView()
    var ball2: UIView = UIView()
    var ball3: UIView = UIView()
    var _ballWidth: CGFloat = 13
    var ballContainer: UIVisualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .light))
    
    func initBallView() {
        ballContainer.frame = CGRect(x: 0, y: 0, width: 120, height: 120)
        ballContainer.center = CGPoint(x: bounds.size.width / 2.0, y: bounds.size.height / 2.0)
        ballContainer.layer.cornerRadius = 10.0
        ballContainer.layer.masksToBounds = true
        ballContainer.backgroundColor = UIColor.clear
        addSubview(ballContainer)

        let margin: CGFloat = 3.0

        ball1 = UIView(frame: CGRect(x: 0, y: 0, width: _ballWidth, height: _ballWidth))
        ball1.center = CGPoint(x: _ballWidth / 2.0 + margin, y: ballContainer.bounds.size.height / 2.0)
        ball1.layer.cornerRadius = _ballWidth / 2.0
        ball1.backgroundColor = UIColor(red: 54 / 255.0, green: 136 / 255.0, blue: 250 / 255.0, alpha: 1)
        ballContainer.contentView.addSubview(ball1)
        
        ball2 = UIView(frame: CGRect(x: 0, y: 0, width: _ballWidth, height: _ballWidth))
        ball2.center = CGPoint(x: ballContainer.bounds.size.width / 2.0, y: ballContainer.bounds.size.height / 2.0)
        ball2.layer.cornerRadius = _ballWidth / 2.0
        ball2.backgroundColor = UIColor(red: 100 / 255.0, green: 100 / 255.0, blue: 100 / 255.0, alpha: 1)
        ballContainer.contentView.addSubview(ball2)

        ball3 = UIView(frame: CGRect(x: 0, y: 0, width: _ballWidth, height: _ballWidth))
        ball3.center = CGPoint(x: ballContainer.bounds.size.width - _ballWidth / 2.0 - margin, y: ballContainer.bounds.size.height / 2.0)
        ball3.layer.cornerRadius = _ballWidth / 2.0
        ball3.backgroundColor = UIColor(red: 234 / 255.0, green: 67 / 255.0, blue: 69 / 255.0, alpha: 1)
        ballContainer.contentView.addSubview(ball3)
    }
    
    func startPathAnimation() {
        let ballScale: CGFloat = 1.3
        //-------第一个球的动画
        let width = ballContainer.bounds.size.width
        //小圆半径
        let r: CGFloat = (ball1.bounds.size.width) * ballScale / 2.0
        //大圆半径
        let R = (width / 2 + r) / 2.0

        let path1 = UIBezierPath()
        path1.move(to: ball1.center)
        //画大圆
        path1.addArc(withCenter: CGPoint(x: R + r, y: width / 2), radius: R, startAngle: .pi, endAngle: .pi * 2, clockwise: false)
        //画小圆
        let path1_1 = UIBezierPath()
        path1_1.addArc(withCenter: CGPoint(x: width / 2, y: width / 2), radius: r * 2, startAngle: .pi * 2, endAngle: .pi, clockwise: false)
        path1.append(path1_1)
        //回到原处
        path1.addLine(to: ball1.center)
        //执行动画
        let positionAnimation = CAKeyframeAnimation(keyPath: "position")
        positionAnimation.path = path1.cgPath
        positionAnimation.isRemovedOnCompletion = false
        positionAnimation.repeatCount = MAXFLOAT
        positionAnimation.duration = 1.6
        positionAnimation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
        ball1.layer.add(positionAnimation, forKey: "animation1")
        
        
        //-------第三个球的动画
        let path3 = UIBezierPath()
        path3.move(to: ball3.center)
        //画大圆
        path3.addArc(withCenter: CGPoint(x: width - (R + r), y: width / 2), radius: R, startAngle: 2 * .pi, endAngle: .pi, clockwise: false)
        //画小圆
        let path3_1 = UIBezierPath()
        path3_1.addArc(withCenter: CGPoint(x: width / 2, y: width / 2), radius: r * 2, startAngle: .pi, endAngle: .pi * 2, clockwise: false)
        path3.append(path3_1)
        //回到原处
        path3.addLine(to: ball3.center)
        //执行动画
        let animation3 = CAKeyframeAnimation(keyPath: "position")
        animation3.path = path3.cgPath
        animation3.repeatCount = MAXFLOAT
        animation3.isRemovedOnCompletion = false
        animation3.duration = 1.6
        animation3.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
        ball3.layer.add(animation3, forKey: "animation3")
        
        // 放大缩小动画
        let scaleAnimation = createBasicAnimation(withKeyPath: "transform.scale")
        scaleAnimation.fromValue = 1.0
        scaleAnimation.toValue = 1.3
        scaleAnimation.duration = 1.6/2
        scaleAnimation.isRemovedOnCompletion = false
        scaleAnimation.repeatCount = MAXFLOAT
        scaleAnimation.autoreverses = true
        scaleAnimation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
        ball1.layer.add(scaleAnimation, forKey: "scale")
        ball2.layer.add(scaleAnimation, forKey: "scale")
        ball3.layer.add(scaleAnimation, forKey: "scale")
    }
}

调用

let view = MGSquaresAnimationView(animationViewType: .Square(animationLayerTintColor: UIColor.red, squareSize: 60))
//        let view = MGSquaresAnimationView(animationViewType: .Circle(ballWidth: 30))
self.view.addSubview(view)
view.startAnimating()        
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
     view.stopAnimating()
     view.removeFromSuperview()
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念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

推荐阅读更多精彩内容