首页 > 代码库 > iOS 力学动画生成器UIKit Dynamics 之碰撞效果解说
iOS 力学动画生成器UIKit Dynamics 之碰撞效果解说
UIKit Dynamic是iOS7 新增的一组类和方法。可赋予UIView逼真的行为和特征,不须要写动画效果那些繁琐的代码,让开发者可以轻松地改善应用的用户体验。一共同拥有6个可用于定制UIDynamicAnimator的类。这里先仅仅简介下碰撞的动画效果,即UICollisionBehavior。须要签订一个代理协议:UICollisionBehaviorDelegate。
其它效果,兴许更新,敬请期待。
注意:dragonImageView和frogImageView记得要初始化还有: UIDynamicAnimator、UIGravityBehavior、 UICollisionBehavior一定要声明成属性或者全局变量,否则不会产生动画效果!
#import "ICFCollisionViewController.h"
@interface ICFCollisionViewController ()
{
UIImageView *dragonImageView;
UIImageView*frogImageView;
}
@end
@implementation ICFCollisionViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [superinitWithNibName:nibNameOrNilbundle:nibBundleOrNil];
if (self) {
}
return self;
}
- (void)viewDidLoad
{
[superviewDidLoad];
// 初始化力学动画生成器
UIDynamicAnimator *animator = [[UIDynamicAnimatoralloc]initWithReferenceView:self.view];
// 创建重力下落效果的对象
UIGravityBehavior *gravityBehavior = [[UIGravityBehavioralloc]initWithItems:@[frogImageView,dragonImageView]];
//设置重力加速度。水平和竖直方向
[gravityBehavior setGravityDirection:CGVectorMake(0.0f, 0.3f)];
// 创建碰撞效果的对象
UICollisionBehavior* collisionBehavior = [[UICollisionBehavioralloc]initWithItems:@[frogImageView,dragonImageView]];
// 物体的碰撞模式共同拥有三种:UICollisionBehaviorModeItems(物体相互碰撞)
UICollisionBehaviorModeBoundaries(物体不相互碰撞。仅仅与边界碰撞)
UICollisionBehaviorModeEverything(既与物体碰撞又与边界碰撞)
[collisionBehavior setCollisionMode:UICollisionBehaviorModeEverything];
//此代码的作用是将self.view的边框作为碰撞边界,必须设置为YES,否则不会生成碰撞效果
collisionBehavior.translatesReferenceBoundsIntoBoundary =YES;
[animatoraddBehavior:gravityBehavior];
[animatoraddBehavior:collisionBehavior];
collisionBehavior.collisionDelegate =self;
}
-(void)collisionBehavior:(UICollisionBehavior *)behavior beganContactForItem:(id<UIDynamicItem>)item withBoundaryIdentifier:(id<NSCopying>)identifier atPoint:(CGPoint)p
{
NSLog(@"開始碰撞时触发的方法");
}
-(void)collisionBehavior:(UICollisionBehavior *)behavior endedContactForItem:(id<UIDynamicItem>)item withBoundaryIdentifier:(id<NSCopying>)identifier
{
NSLog(@"结束碰撞时触发的方法");
}
@end
iOS 力学动画生成器UIKit Dynamics 之碰撞效果解说