UIDynamic是苹果IOS7才开始使用的一种技术,是一种物理引擎,实现例如重力,碰撞等现象。
Dynamic初试:实现简单的重力,弹性碰撞效果
UIDynamicAnimator:物理引擎,可以向里面添加重力,弹性碰撞效果
UIGravityBehavior:重力行为
UICollisionBehavior: 弹性碰撞行为
UIDynamicItemBehavior :自定义属性(弹性,密度,摩擦力,旋转,阻力)
简单代码实现
@implementation ViewController
{
UIDynamicAnimator *_animator;
UIGravityBehavior *_gravity;
UICollisionBehavior *_collision;
UIDynamicItemBehavior *_itemDynamic;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIView * square = [[UIView alloc] initWithFrame:CGRectMake(180, 0, 150, 150)];
square.backgroundColor = [UIColor redColor];
[self.view addSubview:square];
UIView * line = [[UIView alloc] initWithFrame:CGRectMake(0, 400, 200, 30)];
line.backgroundColor = [UIColor blueColor];
[self.view addSubview:line];
_animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
//创建重力行为
_gravity = [[UIGravityBehavior alloc] initWithItems:@[square]];
//创建弹性碰撞
_collision = [[UICollisionBehavior alloc] initWithItems:@[square]];
//默认边界是否被使用
_collision.translatesReferenceBoundsIntoBoundary = YES;
CGPoint rightPoint = CGPointMake(line.frame.origin.x + line.frame.size.width, line.frame.origin.y);
NSLog(@"x = %f y = %f", rightPoint.x, rightPoint.y);
//添加弹性碰撞范围
[_collision addBoundaryWithIdentifier:@"line" fromPoint:line.frame.origin toPoint:rightPoint];
_itemDynamic = [[UIDynamicItemBehavior alloc] initWithItems:@[square]];
_itemDynamic.elasticity = 0.9; //设置弹性
_itemDynamic.density = 0.5;//设置密度
_itemDynamic.friction = 0;//设置摩擦力
_itemDynamic.resistance = 0.9;//设置阻力(相对于滑行来说)
_itemDynamic.allowsRotation = YES;//是否允许旋转
_itemDynamic.angularResistance = 0.9;
[_animator addBehavior:_gravity];
[_animator addBehavior:_collision];
}