先看看摩拜貼紙的動畫:
知識點(diǎn)歸納:
- 使用重力行為
- 使用碰撞行為
- 使用彈力行為
- 使用屏幕旋轉(zhuǎn)的傳感器
代碼實(shí)現(xiàn):
- 創(chuàng)建若干個小球(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.創(chuàng)建動畫的播放者
//_animator為全局定義的,否則不會生效,self.view為力學(xué)參考系,動力效果才能生效
_animator = [[UIDynamicAnimator alloc]initWithReferenceView:self.view];
3.創(chuàng)建動力行為,并賦給小球
//添加重力
_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; //彈性系數(shù)
[_animator addBehavior:dyItem];
//還有很多behavior:UIAttachmentBehavior(附著行為)、UISnapBehavior(捕捉行為)、UIPushBehavior(推動行為)、UIDynamicItemBehavior(動力元素行為)
4.創(chuàng)建檢測屏幕旋轉(zhuǎn)的傳感器,并計(jì)算新的弧度給重力行為屬性賦值
-(void)initGyroManager
{
self.motionManager = [[CMMotionManager alloc]init];
self.motionManager.deviceMotionUpdateInterval = 0.01;
[self.motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMDeviceMotion * _Nullable motion, NSError * _Nullable error) {
//返回至原點(diǎn)的方位角
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進(jìn)階 - UIDynamic以及iOS的一些傳感器。
此篇博客的Demo地址