@interface ViewController ()
@property (nonatomic,strong) UIImageView *imageView
@property (nonatomic,strong) CABasicAnimation *anim
@property (nonatomic,strong) CALayer *imageLayer
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad]
[self.view addSubview:self.imageView]
[self.view.layer addSublayer:self.imageLayer]
}
- (CALayer *)imageLayer {
if (!_imageLayer) {
_imageLayer = [CALayer layer]
_imageLayer.frame = CGRectMake(100, 150, 100, 100)
_imageLayer.backgroundColor = [UIColor redColor].CGColor
_imageLayer.contents = (id)[UIImage imageNamed:@"zrx4.jpg"].CGImage
}
return _imageLayer
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[self.imageView.layer addAnimation:self.anim forKey:nil]
}
- (CABasicAnimation *)anim {
if (!_anim) {
//1.创建动画对象
_anim = [CABasicAnimation animation]
//2.设置动画属性.
_anim.keyPath = @"position.y"
_anim.toValue = @(400)
//动画完成时会自动删除动画
_anim.removedOnCompletion = YES
//动画完成时保持什么状态
_anim.fillMode = kCAFillModeForwards
}
return _anim
}
///创建UIImageView
- (UIImageView *)imageView {
if (!_imageView) {
_imageView = [[UIImageView alloc] init]
_imageView.frame = CGRectMake(100, 100, 30, 30)
_imageView.contentMode = UIViewContentModeScaleAspectFit
_imageView.backgroundColor = [[UIColor redColor] colorWithAlphaComponent:0.6]
}
return _imageView
}
@end
