iOS动画动画iOS绘图与动画

iOS 动画 —— 掉落的蘑菇

2016-07-26  本文已影响548人  天空中的球

UIDynamic Animation是iOS 7引入的一个动态库,用来模拟现实世界的物理模型,用掉落的蘑菇暂看看其基本的特性。

mushroom.gif
#import "ViewController.h"

@interface ViewController ()

@property (nonatomic, strong) UIDynamicAnimator *animator;
@property (nonatomic, strong) UIGravityBehavior *gravityBeahvior;
@property (nonatomic, strong) UICollisionBehavior *collisionBehavior;
@property (nonatomic, strong) UIDynamicItemBehavior *itemBehavior;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    UIGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self  action:@selector(tapped:)];
    [self.view addGestureRecognizer:gesture];
    [self setUpDownMushroom];
}

- (void)dealloc {
    [self.animator removeAllBehaviors];
}

- (void)setUpDownMushroom {
    // 相当于一个容器,为下面动画提供上下文
    self.animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
    // 重力
    self.gravityBeahvior = [[UIGravityBehavior alloc] init];
    // 碰撞
    self.collisionBehavior = [[UICollisionBehavior alloc] init];
    // 碰撞边界为可碰撞边界
    self.collisionBehavior.translatesReferenceBoundsIntoBoundary = YES;
    // 物体属性
    self.itemBehavior = [[UIDynamicItemBehavior alloc] init];
    self.itemBehavior.elasticity = 0.7; // 改变弹性
    self.itemBehavior.friction = 0.5; // 摩擦
    self.itemBehavior.resistance = 0.5; // 阻力
    
    [self.animator addBehavior:self.gravityBeahvior];
    [self.animator addBehavior:self.collisionBehavior];
    [self.animator addBehavior:self.itemBehavior];
}

- (void)tapped:(UITapGestureRecognizer *)gesture {
    
    UIImage *image = [UIImage imageNamed:@"mushroom"];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    [self.view addSubview:imageView];
    
    CGPoint tappedPosition = [gesture locationInView:gesture.view];
    imageView.center = tappedPosition;
    
    [self.gravityBeahvior addItem:imageView];
    [self.collisionBehavior addItem:imageView];
    [self.itemBehavior addItem:imageView];
}
@end

简单了解下,上述用到的三大类:

三个类对应的关系

此处作为抛砖引玉,什么是 UIKit Dynamics 这篇博文非常详细,要用到这块的时候,可一步一步的去了解。

PS:场景来自:【iOS开发范例实战宝典.进阶篇】。

上一篇下一篇

猜你喜欢

热点阅读