摩拜贴纸的仿真动画以及传感器

2017-09-29  本文已影响205人  Miss_DQ

先看看摩拜贴纸的动画:

知识点归纳:

代码实现:

  1. 创建若干个小球(UIImageView)
    NSMutableArray *ballViewArr = [NSMutableArray array];
    for(int i=0;i<imageArr.count;i++)
    {
        UIImageView * imgView = [[UIImageView alloc]initWithFrame:CGRectMake(arc4random()%((int)(self.view.bounds.size.width-diameter)), 0, diameter, diameter)];
        imgView.image = [UIImage imageNamed:imageArr[i]];
        imgView.layer.masksToBounds = YES;
        imgView.layer.cornerRadius = diameter/2;
        [self.view addSubview:imgView];
        
        [ballViewArr addObject:imgView];
    }

2.创建动画的播放者

    //_animator为全局定义的,否则不会生效,self.view为力学参考系,动力效果才能生效
    _animator = [[UIDynamicAnimator alloc]initWithReferenceView:self.view];

3.创建动力行为,并赋给小球

    //添加重力
    _gravity = [[UIGravityBehavior alloc]initWithItems:ballViewArr];
    [_animator addBehavior:_gravity];
    
    //添加碰撞
    UICollisionBehavior *collision = [[UICollisionBehavior alloc]initWithItems:ballViewArr];
    collision.translatesReferenceBoundsIntoBoundary = YES;
    [_animator addBehavior:collision];
    
    //添加弹性
    UIDynamicItemBehavior *dyItem = [[UIDynamicItemBehavior alloc]initWithItems:ballViewArr];
    dyItem.allowsRotation = YES;
    dyItem.elasticity = 0.8;        //弹性系数
    [_animator addBehavior:dyItem];
    
    //还有很多behavior:UIAttachmentBehavior(附着行为)、UISnapBehavior(捕捉行为)、UIPushBehavior(推动行为)、UIDynamicItemBehavior(动力元素行为)

4.创建检测屏幕旋转的传感器,并计算新的弧度给重力行为属性赋值

-(void)initGyroManager
{
    self.motionManager = [[CMMotionManager alloc]init];
    self.motionManager.deviceMotionUpdateInterval = 0.01;
    
    [self.motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMDeviceMotion * _Nullable motion, NSError * _Nullable error) {
        //返回至原点的方位角
        double rotation = atan2(motion.attitude.pitch, motion.attitude.roll);
        NSLog(@"rotation:%f",motion.attitude.pitch);
        self.gravity.angle = rotation;
    }];
}
-(void)dealloc
{
    [self.motionManager stopDeviceMotionUpdates];
}

这样,代码就搞定咯。另外可以参考:iOS进阶 - UIDynamic以及iOS的一些传感器

此篇博客的Demo地址

上一篇 下一篇

猜你喜欢

热点阅读