UIDynamic 学习与球形碰撞

#UIDynamic

相关英文单词:Dynamic(动态的)、Gravity(重力)、Collision(碰撞)、Snap(折断)、Push(推动)、Attachment(附属物,依附)、angular velocity(角速度)、 linear velocity(线速度)、elasticity(弹性)、friction(摩擦)、density(密度)、resistance(抗力)

能模拟和仿真现实生活中的物理现象重力、弹性碰撞等现象

##UIDynamic使用步骤

+ 创建一个物理仿真器(顺便设置仿真范围)

+ 创建相应的物理仿真行为(顺便添加物理仿真元素)

+ 将物理仿真行为添加到物理仿真器中,开始仿真

##哪些对象才能做物理仿真元素?

任何遵守了UIDynamicItem协议的对象

UIView默认已经遵守了UIDynamicItem协议,因此任何UI控件都能做物理仿真

UICollectionViewLayoutAttributes类默认也遵守UIDynamicItem协议

##物理仿真行为

+ UIGravityBehavior:重力行为

+ UICollisionBehavior:碰撞行为

+ UISnapBehavior:捕捉行为

+ UIPushBehavior:推动行为

+ UIAttachmentBehavior:附着行为

+ UIDynamicItemBehavior:动力元素行为

###插曲(创建一个球形View)

在实现碰撞动作时候,发现创建的View都是矩形的Frame,即使改变View的cornerRadius让View看起来想一个球形,事实上发生碰撞的边缘依旧是矩形的边框。一下做法可以创建出一个真正意义上的球形View:适用于iOS 9及以后系统。学习:http://blog.csdn.net/dazeng1990/article/details/50454716

**1.自定义一个View继承自UIView,重写collisionBoundsType属性。**

`@interface SKCircleView : UIView

@property (nonatomic) UIDynamicItemCollisionBoundsType collisionBoundsType;

@end

`

`

@implementation SKCircleView

@synthesize collisionBoundsType;

@end

`

**2.调用中重新设置collisionBoundsType属性**

`_grayView = [[SKCircleView alloc] initWithFrame:CGRectMake(80, 100, 50, 50)];

_grayView.layer.cornerRadius = 25;

_grayView.collisionBoundsType = UIDynamicItemCollisionBoundsTypeEllipse;

_grayView.backgroundColor = [UIColor grayColor];

`

**3.主要代码**

UIGravityBehavior *gravityBehavior = [[UIGravityBehavior alloc] init];

[gravityBehavior addItem:_yellowView];

gravityBehavior.magnitude = 1;

//碰撞

UICollisionBehavior  *collisionBehavior = [[UICollisionBehavior alloc] init];

collisionBehavior.collisionMode = UICollisionBehaviorModeEverything;

collisionBehavior.translatesReferenceBoundsIntoBoundary = YES;

[collisionBehavior addItem:_yellowView];

[collisionBehavior addItem:_blueView];

[collisionBehavior addItem:_grayView];

//

UIDynamicItemBehavior* propertiesBehavior = [[UIDynamicItemBehavior alloc] initWithItems:@[_yellowView,_blueView,_grayView]];

propertiesBehavior.elasticity = 1;

propertiesBehavior.allowsRotation = YES;

propertiesBehavior.friction = 1;

[self.dynamicAnimator addBehavior:gravityBehavior];

[self.dynamicAnimator addBehavior:collisionBehavior];

[self.dynamicAnimator addBehavior:propertiesBehavior];

你可能感兴趣的:(UIDynamic 学习与球形碰撞)