今天给大家介绍一下我们iOS开发中不太常用的UIDynamic(当然只是对于非游戏类开发人员说不常用了),我们研究它可以做一些有趣的效果,下面我们先来看一下关于UIDynamic.
一、简单介绍
1.什么是UIDynamic
UIDynamic是从iOS 7开始引入的一种新技术,隶属于UIKit框架
可以认为是一种物理引擎,能模拟和仿真现实生活中的物理现象
如:重力、弹性碰撞等现象
2.物理引擎的价值
广泛用于游戏开发,经典成功案例是“愤怒的小鸟”
让开发人员可以在远离物理学公式的情况下,实现炫酷的物理仿真效果
提高了游戏开发效率,产生更多优秀好玩的物理仿真游戏
3.知名的2D物理引擎
Box2d
Chipmunk
二、使用步骤
要想使用UIDynamic来实现物理仿真效果,大致的步骤如下
- 创建一个物理仿真器(顺便设置仿真范围)
- 创建相应的物理仿真行为(顺便添加物理仿真元素)
- 将物理仿真行为添加到物理仿真器中 (开始仿真)
OK废话不多说直接看一下能实现那些基本的效果
重力行为+碰撞检测 (效果如下图)
重力行为+碰撞检测 (代码实现)
// 当点击屏幕时 灰色Lable自由落体, 与绿色和黄色Lable产生碰撞
#import "ViewController.h"
@interface ViewController ()
// 在storyboard中拖了3个UILable控件
@property (weak, nonatomic) IBOutlet UILabel *grayLable;
@property (weak, nonatomic) IBOutlet UILabel *yellowLable;
@property (weak, nonatomic) IBOutlet UILabel *greenLable;
// 物理仿真器
@property (strong, nonatomic) UIDynamicAnimator *animator ;
@end
@implementation ViewController
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//1.物理仿真器
self.animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
//2.1创建碰撞行为
// items 设置可以碰撞元素
UICollisionBehavior *collision = [[UICollisionBehavior alloc] initWithItems:@[self.grayLable, self.yellowLable, self.greenLable]];
// 以 参数的view 为边界
collision.translatesReferenceBoundsIntoBoundary = YES;
// 2.2创建“重力”仿真行为
// items指定 可以仿真 “重力”行为元素
UIGravityBehavior *gravity = [[UIGravityBehavior alloc] initWithItems:@[self.grayLable]];
// 3.1把 重力行为 添加到 仿真器
[self.animator addBehavior:gravity];
// 3.2把碰撞行为 添加 到仿真器
[self.animator addBehavior:collision];
}
@end
捕捉行为
可以让物体迅速冲到某个位置(捕捉位置),捕捉到位置之后会带有一定的震动
效果图如下
捕捉行为 (代码实现)
#import "ViewController.h"
@interface ViewController ()
// 在storyboard拖了一个UIImageView控件,并设置图片
@property (weak, nonatomic) IBOutlet UIImageView *pictureView;
// 物理仿真器
@property (strong, nonatomic) UIDynamicAnimator *animatior ;
@end
@implementation ViewController
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
// 获取触摸点
UITouch *touch = [touches anyObject];
CGPoint point = [touch locationInView:touch.view];
//捕捉行为
//1.物理仿真器
self.animatior = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
// 2.创建捕捉行为
// 只要遵守UIDynamicItem协议的对象,我们称这个对象为 “物理仿真元素”
UISnapBehavior *snapBehavior = [[UISnapBehavior alloc] initWithItem:self.pictureView snapToPoint:point];
// dampoint取值只能 0~1
// 振幅的幅度 值越小幅度越大,值越大幅度越小
snapBehavior.damping = 0.3;
// 3.把捕捉行为 添加到 仿真器
[self.animatior addBehavior:snapBehavior];
}
UIDynamic提供了以下几种物理仿真行为
UIGravityBehavior:重力行为
UICollisionBehavior:碰撞行为
UISnapBehavior:捕捉行为
UIPushBehavior:推动行为
UIAttachmentBehavior:附着行为
UIDynamicItemBehavior:动力元素行为