iOS物理引擎UIDynamic是在iOS7引入的一项新技术,隶属于UIKit框架,可以让制作物理动画更简单;
主要步骤:
1. 创建一个物理仿真器,设置作用的视图;
2. 创建物理仿真行为,并且添加元素;
3. 将仿真行为添加到仿真器内,开始执行;
物理行为:
UIGravityBehavior:重力行为
UICollisionBehavior:碰撞行为
UISnapBehavior:捕捉行为
UIPushBehavior:推动行为
UIAttachmentBehavior:附着行为
UIDynamicItemBehavior:动力元素行为
所有物理仿真行为都继承自UIDynamicBehavior
所有的UIDynamicBehavior都可以独立进行
组合使用多种行为时,可以实现一些比较复杂的效果
实例:
首先创建动力仿真器
#pragma mark ********** 物理仿真器
-(UIDynamicAnimator *)dyAnimator {
if (!_dyAnimator) {
_dyAnimator = [[UIDynamicAnimator alloc]initWithReferenceView:self.view];
}
return _dyAnimator;
}
各个行为的头文件可以自己去查
一、重力行为
可以设置重力加速度的方向、角度、加速度
UIGravityBehavior *gravity = [[UIGravityBehavior alloc]init];
//重力加速度
gravity.magnitude = 10;
//重力角度
gravity.angle = 0.5;
//添加元素
[gravity addItem:self.imagV];
//添加完成后自动运行
[self.dyAnimator addBehavior:gravity];
二、碰撞行为
同样碰撞行为需要添加元素,把需要碰撞效果的元素添加到碰撞行为内;然后就是设置碰撞的边界(有一个属性设置屏幕边界为碰撞边界);
碰撞还能监听整个碰撞过程
UICollisionBehavior *collison = [[UICollisionBehavior alloc]init];
[collison addItem:self.imagV];
collison.translatesReferenceBoundsIntoBoundary = YES;
[self.dyAnimator addBehavior:collison];
碰撞可以添加<一条直线>为碰撞边界,也可以通过添加一个标记符的<贝塞尔曲线>为边界;
三、捕捉行为
UISnapBehavior初始化时需要设置一个点,存在一个防震系数,值越大振幅越小;如果想多次操作一个behavior可以使用removeAllBehaviors移除所有的行为在添加即可;
UISnapBehavior *snap = [[UISnapBehavior alloc]initWithItem:self.imagV snapToPoint:CGPointMake(200, 300)];
snap.damping = 0.1;
[self.dyAnimator addBehavior:snap];
四、UIPushBehavior
//UIPushBehaviorModeInstantaneous 力是瞬时的
//UIPushBehaviorModeContinuous 力是连续的
//active 创建了之后默认是YES 用这个属性来决定这个行为是否执行
UIPushBehavior *push = [[UIPushBehavior alloc]initWithItems:@[self.imagV] mode:UIPushBehaviorModeContinuous];
push.angle = 0.5;
push.magnitude = 1;
[push setTargetOffsetFromCenter:UIOffsetMake(50, 50) forItem:self.imagV];
[self.dyAnimator addBehavior:push];
五、UIAttachmentBehavior
UIOffset offset = UIOffsetMake(self.squareViewAnchorView.center.x, self.squareViewAnchorView.center.y);
self.attachmentBehavior = [[UIAttachmentBehavior alloc] initWithItem:self.squareView
offsetFromCenter:offset //偏移
attachedToAnchor:self.anchorView.center];
[self.dyAnimator addBehavior:collision];
[self.dyAnimator addBehavior:self.attachmentBehavior];
六、UIDynamicItemBehavior
-动画效果:增加各种物理特性
//指派不同特性值 弹性bounce
UIDynamicItemBehavior *moreElasticItem = [[UIDynamicItemBehavior alloc]
initWithItems:@[bottomView]];
moreElasticItem.elasticity = 1.0f;
UIDynamicItemBehavior *lessElasticItem = [[UIDynamicItemBehavior alloc]
initWithItems:@[topView]];
lessElasticItem.elasticity = 0.5f;
[self.dyAnimator addBehavior:moreElasticItem];
[self.dyAnimator addBehavior:lessElasticItem];