iOS 力學動畫產生器UIKit Dynamics 之碰撞效果講解,uikitdynamics
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