[Swift]利用CATransform3D实现翻转动画

CATransform3D.gif

1.利用手势滑动UIPanGestureRecognizer 判断手势拖动的坐标
2.利用CATransform3DRotate实现拖动过程图片翻转
3.利用手势禁用范围实现轮播图scrollView翻页

核心代码

 @objc fileprivate func panInCard(_ panGes: UIGestureRecognizer) {
        let touchPoint = panGes.location(in: imageView)
        if panGes.state == .changed {
            UserDefaults.standard.set(true, forKey: IS_GESTURE_PAN)
            NotificationCenter.default.post(name: PanInCardNotify, object: nil, userInfo: ["changed" : true])

            let xFactor = myMIN(1, myMAX(-1, (touchPoint.x - (self.bounds.size.width / 2)) / (self.bounds.size.width / 2) ))
            let yFactor = myMIN(1, myMAX(-1, (touchPoint.y - (self.bounds.size.height / 2)) / (self.bounds.size.height / 2) ))
            imageView.layer.anchorPoint = CGPoint(x: 0.5, y: 0.5)

            imageView.layer.transform = self.imagePanTransform(m34: 1.0 / CGFloat(-500), xf: xFactor, yf: yFactor)
            
//            let zFactor = 180.0 * atan(yFactor / xFactor) / CGFloat(Double.pi) + 90
//            printLog(zFactor)
            
        } else if panGes.state == .ended {
            NotificationCenter.default.post(name: PanInCardNotify, object: nil, userInfo: ["changed" : false])
            UIView.animate(withDuration: kSpreadDuration, animations: {
                self.imageView.layer.transform = CATransform3DIdentity
            }, completion: nil)
        }
    }
    
    fileprivate func imagePanTransform(m34: CGFloat, xf: CGFloat, yf: CGFloat) -> CATransform3D {
        var t = CATransform3DIdentity
        t.m34 = m34
        t = CATransform3DRotate(t, CGFloat(Double.pi) / 15 * yf , -1, 0, 0)
        
        //t: CATransform3D, t: CATransform3D, x: CGFloat, y: CGFloat, z: CGFloat 后面3个数字分别代表不同的轴来翻转
        // xf / 360.0 * 2.0 * CGFloat(Double.pi)  
        t = CATransform3DRotate(t, CGFloat(Double.pi) / 15 * xf , 0, 1, 0)
        return t
        
    }

 func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        if touch.view == emptyView {
            //#UIGestureRecognizerDelegate
            //我在这里设置响应事件的优先级,因为UITap响应事件的优先级会高,则他的subview的事件会被阻止
            return false
        }
        return true
    }
    

PanInCardNotify 通知的目的是在拖动动画实现的过程时能够清除轮播图定时器和添加定时器

你可能感兴趣的:([Swift]利用CATransform3D实现翻转动画)