iOS 自定义弹性碰撞效果View

类似一堆乒乓球的相互碰撞效果
核心代码:


#import "ViewController.h"

@interface ViewController ()

@property (nonatomic, strong) NSMutableArray *balls;
@property (nonatomic, strong) UIGravityBehavior *gravityBeahvior;
@property (nonatomic, strong) UIGravityBehavior *gravity;
@property (nonatomic, strong) UICollisionBehavior *collision;
@property (nonatomic, strong) UIDynamicAnimator *animator;
@property (nonatomic, strong) UIDynamicItemBehavior *dynamicItemBehavior;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.balls = [NSMutableArray array];
    
    UIButton *clickBtn = [UIButton new];
    [clickBtn addTarget:self action:@selector(setupBalls) forControlEvents:UIControlEventTouchUpInside];
    [clickBtn setBackgroundColor:[UIColor redColor]];
    [clickBtn setTitle:@"开始碰撞" forState:UIControlStateNormal];
    [clickBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.view addSubview:clickBtn];
    clickBtn.frame = CGRectMake((self.view.frame.size.width - 80)/2, 80, 80, 40);
    
    self.view.backgroundColor = [UIColor colorWithRed:24/255.f green:24/255.f blue:24/255.f alpha:1.f];

}

- (void)setupBalls{
   
    for (UIImageView *imageView in self.balls) {
        [imageView removeFromSuperview];
    }
    
    [self.balls removeAllObjects];
    
    //添加两个球体,使用拥有重力特性和碰撞特性
    NSUInteger numOfBalls = 20;
    for (NSUInteger i = 0; i < numOfBalls; i ++) {
        
        UIImageView *ball = [UIImageView new];
        
        //球的随机颜色
        ball.image = [UIImage imageNamed:[NSString stringWithFormat:@"headIcon-%ld.jpg",i]];
        
        //球的随机大小:40~60之间
        CGFloat width = 40;
        ball.layer.cornerRadius = width/2;
        ball.layer.masksToBounds = YES;
        
        //球的随机位置
        CGRect frame = CGRectMake(arc4random()%((int)(self.view.bounds.size.width - width)), 0, width, width);
        [ball setFrame:frame];
        
        //添加球体到父视图
        [self.view addSubview:ball];
        //球堆添加该球
        [self.balls addObject:ball];
    }
    
    UIDynamicAnimator *animator     = [[UIDynamicAnimator alloc]initWithReferenceView:self.view];
    _animator                       = animator;
    
    //添加重力的动态特性,使其可执行
    UIGravityBehavior *gravity = [[UIGravityBehavior alloc]initWithItems:self.balls];
    [self.animator addBehavior:gravity];
    _gravity = gravity;
    
    //添加碰撞的动态特性,使其可执行
    UICollisionBehavior *collision = [[UICollisionBehavior alloc]initWithItems:self.balls];
    collision.translatesReferenceBoundsIntoBoundary = YES;
    [self.animator addBehavior:collision];
    _collision = collision;
    
    //弹性
    UIDynamicItemBehavior *dynamicItemBehavior = [[UIDynamicItemBehavior alloc] initWithItems:self.balls];
    dynamicItemBehavior.allowsRotation = YES;//允许旋转
    dynamicItemBehavior.elasticity = 0.6;//弹性
    [self.animator addBehavior:dynamicItemBehavior];
}

你可能感兴趣的:(iOS 自定义弹性碰撞效果View)