iOS 图片遮罩动画,图片逐渐显示


class AnimationController: UIViewController {

    /// 背景图
    private lazy var bgView: UIImageView = {
        let view = UIImageView(image: UIImage(named: "img1"))
        return view
    }()
    
    /// 动画显示图片
    lazy var animateView: UIImageView = {
        let view = UIImageView(image: UIImage(named: "img"))
        return view
    }()
    
    /// 遮罩动画 layer
    private var animateLayer: CAShapeLayer?

    var timer: Timer?
    
    var tmpH: CGFloat = 0.1
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.addSubview(bgView)
        view.addSubview(animateView)
        bgView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.width.equalTo(200)
            make.height.equalTo(500)
        }
        animateView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.width.equalTo(200)
            make.height.equalTo(500)
        }
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        startAnimationTimer()
    }
}


extension AnimationController {
    
    private func startAnimationTimer() {
        destroyAnimationTimer()
        timer = Timer(timeInterval: 0.001, repeats: true, block: { [weak self]_ in
            guard let weakSelf = self else { return
            }
            weakSelf.tmpH += 0.1
            weakSelf.addMaskLayer(progress: Float(weakSelf.tmpH))
        })
        RunLoop.current.add(timer!, forMode: .common)
        timer?.fire()
    }
    
    private func destroyAnimationTimer() {
        timer?.invalidate()
        timer = nil
    }
}


extension AnimationController {
    
    private func addMaskLayer(progress: Float) {
        let viewWidth = animateView.frame.width
        let viewHeight = animateView.frame.height
        let tmpHeight = CGFloat(progress)

        animateLayer?.removeFromSuperlayer()
        animateLayer = nil
        let point1 = CGPoint(x: 0, y: 0)
        let point2 = CGPoint(x: viewWidth, y: 0)
        let point3 = CGPoint(x: viewWidth, y: tmpHeight)
        let point4 = CGPoint(x: 0, y: tmpHeight)
        let path = UIBezierPath()
        path.move(to: point1)
        path.addLine(to: point2)
        path.addLine(to: point3)
        path.addLine(to: point4)
        path.close()
        animateLayer = CAShapeLayer()
        animateLayer?.path = path.cgPath
        animateView.layer.mask = animateLayer
    }
}

iOS中layer之mask 详解 - 简书

你可能感兴趣的:(iOS,ios,objective-c,开发语言)