IOS-UIDynamic
UIDynamic中的三个重要概念
// 实例化一个重力行为,并传入需要做动力仿真的对象view
UIGravityBehavior *gravity = [[UIGravityBehavior alloc] initWithItems:@[view]];
// 将重力行为添加到animator
[animator addBehavior:gravity];// 实例化碰撞行为,并指定view参与碰撞
UICollisionBehavior *collsion = [[UICollisionBehavior alloc] initWithItems:@[view]];
// 指定是否启用参照系的边界
collsion.translatesReferenceBoundsIntoBoundary = YES;
// 将碰撞行为添加至animator
[animator addBehavior:collsion];
吸附行为(Snap)
/ 删除之前的吸附行为
[_animator removeBehavior:_snap];
CGPoint location = [sender locationInView:self.view];
_snap = [[UISnapBehavior alloc] initWithItem:_boxImageView snapToPoint:location];
// 生成随机振幅
CGFloat damping = arc4random_uniform(10) + 1;
_snap.damping = damping / 10.0f;
[_animator addBehavior:_snap];
if (UIGestureRecognizerStateBegan == sender.state) {
// 创建附加刚性行为
CGPoint anchorPoint = CGPointMake(_boxImageView.center.x, _boxImageView.center.y);
_attachment = [[UIAttachmentBehavior alloc] initWithItem:_boxImageView offsetFromCenter:UIOffsetMake(-25.0, -25.0) attachedToAnchor:anchorPoint];
[_animator addBehavior:_attachment];
} else if (UIGestureRecognizerStateChanged == sender.state) {
// 设置行为的锚点
[_attachment setAnchorPoint:[sender locationInView:self.view]];
} else if (UIGestureRecognizerStateEnded == sender.state) {
// 删除附加行为
[_animator removeBehavior:_attachment];
}
//附加弹性行为
if (UIGestureRecognizerStateBegan == sender.state) {
CGPoint anchor = CGPointMake(_boxImageView.center.x, _boxImageView.center.y - 100);
_attachment = [[UIAttachmentBehavior alloc] initWithItem:_boxImageView attachedToAnchor:anchor];
[_animator addBehavior:_attachment];
[_attachment setFrequency:1.0f];
[_attachment setDamping:0.1f];
} else if (UIGestureRecognizerStateChanged == sender.state) {
[_attachment setAnchorPoint:[sender locationInView:self.view]];
} else if (UIGestureRecognizerStateEnded == sender.state) {
[_animator removeBehavior:_attachment];
}
// 计算两点之间距离
CGFloat distance = sqrtf(powf(p.x - _firstPoint.x, 2.0) + powf(p.y - _firstPoint.y, 2.0));
CGFloat angle = atan2(p.y - _firstPoint.y, p.x - _firstPoint.x);
_push.magnitude = distance / 20;
_push.angle = angle;
[_push setActive:YES];