美文网首页iOS日常
UIDynamic动画

UIDynamic动画

作者: BigBowen | 来源:发表于2017-12-05 16:48 被阅读7次

    基础知识

    UIDynamic是物理仿真动画,使用前先了解三个类:
    物理仿真元素(Dynamic Item):要执行动画的元素,需要遵守UIDynamicItem协议,对于UIView我们直接使用即可,它已经遵守了.

    物理仿真行为(Dynamic Behavior):要执行的仿真行为,例如仿重力下降,仿物体碰到障碍物,目前提供的仿真行为有: UIGravityBehavior(重力行为),UICollisionBehavior(碰撞行为),UISnapBehavior(捕捉行为),UIPushBehavior(推动行为),UIAttachmentBehavior(附着行为),UIDynamicItemBehavior(动力元素行为).

    物理仿真器(Dynamic Animator): UIDynamicAnimator,让仿真元素执行仿真动画.

    应用

    实现重力和碰撞的仿真行为动画


    数字1.gif

    class ViewController: UIViewController, UIDynamicAnimatorDelegate { var dynamicAnimator = UIDynamicAnimator() //物理仿真器 var imageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() self.imageView = UIImageView(frame: CGRect.init(x: 50, y: 350, width: 100, height: 100)) self.imageView.backgroundColor = UIColor.red self.imageView.layer.cornerRadius = 50 self.imageView.layer.masksToBounds = true self.view.addSubview(self.imageView) }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        dynamicAnimator = UIDynamicAnimator(referenceView: self.view)
        dynamicAnimator.delegate = self
        let itemBehavior = UIDynamicItemBehavior(items: [self.imageView])
        itemBehavior.elasticity = 0.5
        dynamicAnimator.addBehavior(itemBehavior)
        
        //创建并添加重力行为
        let gravityBehavior = UIGravityBehavior(items: [self.imageView])
        gravityBehavior.magnitude = 1
        //下降的角度
        gravityBehavior.angle = 45
        dynamicAnimator.addBehavior(gravityBehavior)
        
        //创建并添加碰撞行为
        let collisionBehavior = UICollisionBehavior(items: [self.imageView])
        collisionBehavior.translatesReferenceBoundsIntoBoundary = true
        collisionBehavior.collisionMode = .everything
        dynamicAnimator.addBehavior(collisionBehavior)
    }
    
    //监听动画结束
    func dynamicAnimatorDidPause(_ animator: UIDynamicAnimator) {
        self.imageView.frame = CGRect.init(x: 50, y: 350, width: 100, height: 100)
    }
    

    }

    `

    相关文章

      网友评论

        本文标题: UIDynamic动画

        本文链接:https://www.haomeiwen.com/subject/vnpcixtx.html