iOS 动画 —— 橡皮筋

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

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

  • RubberBaseView -- 初始化 View
  • RubberAttachView -- 增加吸附行为
  • RubberView -- 增加弹性行为
#import 

@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 )item attachedToAnchor:(CGPoint)point;
- (instancetype)initWithItem:(id )item offsetFromCenter:(UIOffset)offset attachedToAnchor:(CGPoint)point NS_DESIGNATED_INITIALIZER;

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

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

你可能感兴趣的:(iOS 动画 —— 橡皮筋)