美文网首页iOS动画动画iOS绘图与动画
iOS 动画 —— 掉落的蘑菇

iOS 动画 —— 掉落的蘑菇

作者: 天空中的球 | 来源:发表于2016-07-26 08:43 被阅读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
    
    

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

    • UIDynamicAnimator,封装了底层 iOS 物理引擎,为动力项提供物理相关的功能和动画。(animator)
    • UIDynamicBehavior,动力行为,为动力项提供不同的物理行为(gravityBeahvior、collisionBehavior、itemBehavior)
    • UIDynamicItem,动力项,相当于现实世界中的一个基本物体(imageView)
    三个类对应的关系

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

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

    相关文章

      网友评论

      本文标题:iOS 动画 —— 掉落的蘑菇

      本文链接:https://www.haomeiwen.com/subject/cfdnjttx.html