UIDynamic是蘋果IOS7才開始使用的一種技術(shù)叔壤,是一種物理引擎区端,實現(xiàn)例如重力榴鼎,碰撞等現(xiàn)象伯诬。
Dynamic初試:實現(xiàn)簡單的重力,彈性碰撞效果
UIDynamicAnimator:物理引擎巫财,可以向里面添加重力盗似,彈性碰撞效果
UIGravityBehavior:重力行為
UICollisionBehavior: 彈性碰撞行為
UIDynamicItemBehavior :自定義屬性(彈性,密度平项,摩擦力赫舒,旋轉(zhuǎn),阻力)
簡單代碼實現(xiàn)
@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];
//創(chuàng)建重力行為
_gravity = [[UIGravityBehavior alloc] initWithItems:@[square]];
//創(chuàng)建彈性碰撞
_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; //設(shè)置彈性
_itemDynamic.density = 0.5;//設(shè)置密度
_itemDynamic.friction = 0;//設(shè)置摩擦力
_itemDynamic.resistance = 0.9;//設(shè)置阻力(相對于滑行來說)
_itemDynamic.allowsRotation = YES;//是否允許旋轉(zhuǎn)
_itemDynamic.angularResistance = 0.9;
[_animator addBehavior:_gravity];
[_animator addBehavior:_collision];
}