iOS 动画 —— 橡皮筋

接着上一个动画继续学习UIDynamic Animation 相关,通过 UIGravityBehavior 重力行为、UICollisionBehavior 碰撞行为、UIAttachmentBehavior吸附行为实现橡皮筋的功能。

将其创建为 View,通过子 View 逐一设置来特征

  • RubberBaseView -- 初始化 View
  • RubberAttachView -- 增加吸附行为
  • RubberView -- 增加弹性行为
#import <UIKit/UIKit.h>

@interface RubberBaseView : UIView

@property (nonatomic, strong) UIImageView *box;
@property (nonatomic, strong) UIDynamicAnimator *animator;

@end
#import "RubberBaseView.h"

@implementation RubberBaseView

- (instancetype)initWithFrame:(CGRect)frame {
    
    self = [super initWithFrame:frame];
    if (self) {
        // 设置背景颜色(通过图片)
        self.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"back"]];
        // 设置方块 橡皮
        _box = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"rubber"]];
        _box.center = self.center;
        [self addSubview: _box];
        
        // 创建UIDynamicAnimator
        _animator = [[UIDynamicAnimator alloc] initWithReferenceView:self];
    }
    return self;
}

#import "RubberBaseView.h"

@interface RubberAttachView : RubberBaseView

@property (strong, nonatomic) UIAttachmentBehavior *attachment;

@end

#import "RubberAttachView.h"

@implementation RubberAttachView {
     UIImageView          *_imageView;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        
        //  添加拖动手势
        UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
        [self addGestureRecognizer:pan];
        
        //  添加附着行为
        UIOffset offset = UIOffsetMake(-25, -25);
        _attachment = [[UIAttachmentBehavior alloc] initWithItem:self.box offsetFromCenter:offset attachedToAnchor:CGPointMake(self.box.center.x, self.box.center.y - 100)];
        [self.animator addBehavior:_attachment];
        
        //  添加box内部锚点图像
        _imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"lineCircle"]];
        _imageView.center = CGPointMake(self.box.bounds.size.width / 2 + offset.horizontal, self.box.bounds.size.height / 2 + offset.vertical);
        [self.box addSubview:_imageView];
    }
    return self;
}

- (void)pan:(UIPanGestureRecognizer *)gesture {
    
    if (UIGestureRecognizerStateChanged == gesture.state) {
        self.attachment.anchorPoint = [gesture locationInView:self];
        // 重新绘制
        [self setNeedsDisplay];
    }
}

- (void)drawRect:(CGRect)rect
{
    // 上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    // 位置
    CGPoint position = [self convertPoint:_imageView.center fromView:self.box];
    // 设置开始点
    CGContextMoveToPoint(context, position.x, position.y);
    CGContextAddLineToPoint(context, self.attachment.anchorPoint.x, self.attachment.anchorPoint.y);
    // 设置线宽
    CGContextSetLineWidth(context, 5.0f);
    CGFloat length[] = {5.0, 5.0};
    CGContextSetLineDash(context, 0.0, length, 2);
    [[UIColor blackColor] set];
    // 设置路径
    CGContextDrawPath(context, kCGPathStroke);
}

@end
#import "RubberAttachView.h"

@interface RubberView : RubberAttachView

@end
#import "RubberView.h"

static NSString *const RubberViewCenterKVOName = @"center";

@implementation RubberView

- (instancetype)initWithFrame:(CGRect)frame {
    
    self = [super initWithFrame:frame];
    if (self) {
        // 设置物理属性
        self.attachment.damping = 1; // 震荡
        self.attachment.frequency = 1; // 阻力
        // 设置观察者,在手指离开以后继续画线
        [self.box addObserver:self forKeyPath:RubberViewCenterKVOName options:NSKeyValueObservingOptionNew context:nil];
        
        //创建并添加重力
        UIGravityBehavior *gravity = [[UIGravityBehavior alloc] initWithItems:@[self.box]];
        [self.attachment addChildBehavior:gravity];
        
        //创建并添加碰撞行为对象
        UICollisionBehavior *collision = [[UICollisionBehavior alloc] initWithItems:@[self.box]];
        collision.translatesReferenceBoundsIntoBoundary = YES;
        [self.attachment addChildBehavior:collision];
    }
    return self;
}

- (void)dealloc {
    [self.box removeObserver:self forKeyPath:RubberViewCenterKVOName];
}

//画线
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:RubberViewCenterKVOName]) {
        [self setNeedsDisplay];
    }
    
}
@end

最后实现

#import "ViewController.h"
#import "RubberView.h"

#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height

@interface ViewController ()

@property (nonatomic, strong) RubberView *rubberView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.rubberView];
}

- (RubberView *)rubberView  {
    if (!_rubberView) {
        _rubberView = [[RubberView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    }
    return _rubberView;
}

@end

注意点1: 此处为什么要通过 子类的 View(继承) 逐一去设置呢?

  • 方便理解,一目了解
  • 不改变原来的基础上,拓充方法,扩充功能性强。

当然此处也可以不这样写咯。

注意点2: UIAttachmentBehavior

附着行为,让物体附着在某个点或另外一个物体上。可以设置附着点的到物体的距离,阻尼系数和振动频率等。

_attachment = [[UIAttachmentBehavior alloc] initWithItem:self.box offsetFromCenter:offset attachedToAnchor:CGPointMake(self.box.center.x, self.box.center.y - 100)];

注意这个初始化中方法的offset 和 point 的设置(就是决定线和 box 位置和距离的),当然UIAttachmentBehavior 还有其他的初始化方法,可以根据不同场景相应使用。

- (instancetype)initWithItem:(id <UIDynamicItem>)item attachedToAnchor:(CGPoint)point;
- (instancetype)initWithItem:(id <UIDynamicItem>)item offsetFromCenter:(UIOffset)offset attachedToAnchor:(CGPoint)point NS_DESIGNATED_INITIALIZER;

- (instancetype)initWithItem:(id <UIDynamicItem>)item1 attachedToItem:(id <UIDynamicItem>)item2;
- (instancetype)initWithItem:(id <UIDynamicItem>)item1 offsetFromCenter:(UIOffset)offset1 attachedToItem:(id <UIDynamicItem>)item2 offsetFromCenter:(UIOffset)offset2 NS_DESIGNATED_INITIALIZER;

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 本文中所有代码演示均有GitHub源码,点击下载 UIDynamic简介 简介:UIKit动力学最大的特点是将现实...
    si1ence阅读 13,510评论 8 79
  • 前言: UIKit Dynamics是iOS7.0新增的一组类和方法,可以赋予UIView逼真的行为和特征,从而改...
    Y_小葱阅读 3,933评论 1 1
  • 概念介绍 UIDynamic从ios7才开始有的,其他2D仿真引擎:BOX2D:C语言框架,免费Chipmunk:...
    我是滕先生阅读 6,682评论 5 23
  • 写了一些不敢写 没良心的话 可那是我的真实想法 怕什么呢 那日记不会给谁看 别说不愿说 写也不愿些 欣喜的是 我慢...
    桔树上阅读 1,108评论 0 2
  • 1.OpenCL概念 OpenCL是一个为异构平台编写程序的框架,此异构平台可由CPU、GPU或其他类型的处理器组...
    snoopy_zc阅读 33,859评论 2 18

友情链接更多精彩内容