随手记UIKit Dynamics

时间:2023-03-09 04:05:06
随手记UIKit Dynamics

以今年的优势WWDC品行,我记得一些明年的元素。一些博客上找到了新的功能没有被记录。认为iOS 8全力以赴。iOS 7该属性不随手记录为时已晚 :)

参考WWDC 2013的Session Videos《Getting Started with UIKit Dynamics》和《Advanced Techniques with UIKit Dynamics》。随手记了以下几点:

UIKit Dynamics是抽象出来封装好的二维物理引擎,并自己定义了UIKit物理世界的两个常量,用UIKit重力加速度1000p/s2替换了地球重力加速度,用UIKit牛顿第二定律每一单位的力能够使得100p*100p的view产生100p/s2的加速度来替换1F = 1Kg * 1m/s2。

从使用者的角度来看,UIKit Dynamics有例如以下几个角色:

UIDynamicAnimator —— 封装了底下的物理引擎,使得我们能够方便地加入物理行为;

UIDynamicBehavior —— 定义了物理行为的类型;

UIDynamicItem      —— 參与物理动画的对象;

随手记UIKit Dynamics

随手记UIKit Dynamics

借用两张网上的照片来描写叙述三者之间的关系,分别来自http://www.teehanlax.com/blog/introduction-to-uikit-dynamics/ 和 WWDC 2013。

以下是详细的demo代码。

首先我们创建UIDynamicAnimator:

self.animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];

使用self.view作为參考系。

接着,创建要作用物理动画的视图对象。最好还是为一个label:

    UILabel *label = [[UILabel alloc] initWithFrame:(CGRect){100, 100, 100, 40}];
label.backgroundColor = [UIColor redColor];
[self.view addSubview:label];

于是我们能够在label上加入重力加速度和碰撞的物理效果:

    UIGravityBehavior *gravityBehavior = [[UIGravityBehavior alloc] initWithItems:@[label]];
[self.animator addBehavior:gravityBehavior]; UICollisionBehavior *collisionBehavior = [[UICollisionBehavior alloc] initWithItems:@[label]];
collisionBehavior.translatesReferenceBoundsIntoBoundary = YES;
[self.animator addBehavior:collisionBehavior];

这就能创建出十分生动的物理动画了。

除此之外,我们还能够在视图上加上作用力:

    self.pushBehavior = [[UIPushBehavior alloc] initWithItems:@[label] mode:UIPushBehaviorModeInstantaneous];
self.pushBehavior.pushDirection = CGVectorMake(1.0f, 0);
[self.animator addBehavior:self.pushBehavior];

这样。label就不是垂直往下掉了,而是有个水平作用力使得label撞向边缘。

为了使得动画更有趣,能够加点用户的交互:

    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(didPanLabel:)];
[label addGestureRecognizer:panGesture];

为label加入一个拖动手势,相当于作用于label上的力的来源:

#pragma mark - 

- (void)didPanLabel:(UIPanGestureRecognizer *)panGesture
{
UIGestureRecognizerState state = panGesture.state;
if (state == UIGestureRecognizerStateEnded) {
CGPoint velocity = [panGesture velocityInView:self.view];
self.pushBehavior.pushDirection = CGVectorMake(velocity.x / 1000, velocity.y / 1000);
self.pushBehavior.active = YES;
}
}

这项。当用户在施力动作中检测label当顶,label它会抛出。

版权声明:本文博主原创文章,博客,未经同意不得转载。