【iOS】UIDynamic

UIDynamic是从iOS 7开始引入的一种新技术,属于UIKit框架。可以认为是一种物理引擎,能模拟和仿真现实生活中的物理现象:如重力、弹性碰撞等现象。


一、UIDynamic中的一些概念

三个重要的类

UIDynamicItem Protocol:(要执行仿真动画的对象)

To make a custom object eligible to participate in UIKit Dynamics, adopt the UIDynamicItem protocol in the object’s class.
Starting in iOS 7, the UIView and UICollectionViewLayoutAttributes classes implement this protocol.

UIDynamicAnimator Class:(相当于控制者,仿真器)

A dynamic animator provides physics-related capabilities and animations for its dynamic items, and provides the context for those animations. It does this by intermediating between the underlying iOS physics engine and dynamic items, via behavior objects you add to the animator.

UIDynamicBehavior Class:(执行怎样的动画)

A dynamic behavior confers a behavioral configuration on one or more dynamic items for their participation in two-dimensional animation.


二、使用UIDynamic

TIPS

1、遵守了UIDynamicItem协议的对象才能做物理仿真,UIView遵守了,因此能做物理仿真。

2、仿真行为一般继承自UIDynamicBehavior,各个行为即可以独立,也可以组合做出复杂的效果。

UIDynamic提供了以下几种物理仿真行为
UIGravityBehavior:重力行为
UICollisionBehavior:碰撞行为
UISnapBehavior:捕捉行为
UIPushBehavior:推动行为
UIAttachmentBehavior:附着行为
UIDynamicItemBehavior:动力元素行为


一个简单的做重力下落的例子:

#import "XNViewController.h"

@interface XNViewController ()
//1.实例化仿真器
@property (nonatomic, strong) UIDynamicAnimator *animator;
@end

@implementation XNViewController

- (UIDynamicAnimator *)animator {
	if (!_animator) {
		_animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
	}
	return _animator;
}

/**点击屏幕后物体开始重力下落*/
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

	// 2.创建物理仿真行为
	// 创建重力仿真行为 (Items : 仿真元素)
	UIGravityBehavior *gravity = [[UIGravityBehavior alloc] initWithItems:@[self.box]];

	// 创建碰撞仿真行为
	UICollisionBehavior *collision = [[UICollisionBehavior alloc] initWithItems:@[self.box, self.thing]];
	// 指定碰撞的范围
	collision.translatesReferenceBoundsIntoBoundary = YES;

	// 3.将物理仿真行为添加到物理仿真器中
	[self.animator addBehavior:gravity];
	[self.animator addBehavior:collision];
}

@end

点击屏幕后碰撞的效果如下:

【iOS】UIDynamic_第1张图片


源码下载:http://download.csdn.net/detail/xn4545945/7696865


官方文档上有个不错的例子:搜索UIKit Dynamics Catalog打开即可。

这里也有一个不错的例子:http://www.cocoachina.com/bbs/read.php?tid=168779


参考:苹果官方文档

转载请注明出处:http://blog.csdn.net/xn4545945  



你可能感兴趣的:(ios,UIKit,物理引擎,仿真,UIDynamic)