iOS开发心跳动画效果

781 阅读1分钟
#import "ViewController.h"

@interface ViewController ()

@property (nonatomic,strong) UIImageView *imageView;

@end

@implementation ViewController

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

- (UIImageView *)imageView {
    if (!_imageView) {
        _imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
        _imageView.center = CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height/2);
        _imageView.image = [UIImage imageNamed:@"btn-share-wechat"];
        CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
        animation.duration = 1;// 动画时间
        NSMutableArray *values = [NSMutableArray array];
        [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.8, 0.8, 1.0)]];
        [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.2, 1.2, 1.0)]];
        [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.8, 0.8, 1.0)]];
        animation.values = values;
        animation.repeatCount = FLT_MAX;
        [_imageView.layer addAnimation:animation forKey:nil];
    }
    return _imageView;
}

@end

#import "ViewController.h"
#import <Masonry/Masonry.h>

@interface ViewController ()

@property (nonatomic, assign) CGFloat width;
@property (nonatomic, strong) UIImageView *imageView;

@end

@implementation ViewController

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

- (UIImageView *)imageView {
    if (!_imageView) {
        _imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"heart"]];
        [_imageView setContentMode:UIViewContentModeScaleAspectFit];
        _imageView.bounds = CGRectMake(0, 0, 128, 128);
        _imageView.center = self.view.center;
    }
    return _imageView;
}

- (void)animateWithInvertedInsets:(BOOL)invertedInsets {
    self.width = invertedInsets ? 50.0f : 200.0f;
    
    //更新约束
    [self.imageView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(self.width);
        make.center.mas_equalTo(self.view);
    }];
    [UIView animateWithDuration:1.0f animations:^{
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        //repeat!
        [self animateWithInvertedInsets:!invertedInsets];
    }];
}

@end