//创建layer
- (void)createLayer
{
_layer = [[CALayer alloc]init];
//layer.frame = CGRectMake(100, 100, 100, 100);
//设置当前的layer在父图层当前的位置(锚点在父图层中的位置坐标)
_layer.position = CGPointMake(100, 100);
//设置layer的锚点(定位点):取值范围(0,0)-(1,1)
_layer.anchorPoint = CGPointMake(0.5, 0.5);
//设置layer的宽高bounds
_layer.bounds = CGRectMake(0, 0, 100, 100);
_layer.backgroundColor = [UIColor redColor].CGColor;
_layer.cornerRadius = 20;
[self.view.layer addSublayer:_layer];
}
//创建按钮
- (void)createBtn
{
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(50, 450, 100, 40);
[btn setTitle:@"空间操作" forState:UIControlStateNormal];
btn.backgroundColor = [UIColor redColor];
[btn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
}
//创建定时器方法1:平移
- (void)updateTimer
{
//平移操作
//transform:代表图层在控件坐标系中的位置,z轴的移动看不到
//_layer.transform = CATransform3DTranslate(_layer.transform, 5, 5, 0);
//通过KVC设置_layer的值
[_layer setValue:[NSValue valueWithCATransform3D:CATransform3DTranslate(_layer.transform, 5, 5, 0)] forKeyPath:@"translation.x"];
}
//创建定时器方法2:缩放
- (void)updateTimer2
{
//缩放
_layer.transform = CATransform3DScale(_layer.transform, 1, 2, 0);
}
//创建定时器方法3:旋转
- (void)updateTimer3
{
//旋转
//CATransform3D t:当前值
//CGFloat angle : 改变角度
//参数345:XYZ轴
//可以实现沿xyz轴任意旋转(需要设置锚点位置)
_layer.transform = CATransform3DRotate(_layer.transform, M_PI_4/15, 0, 0, 1);
}
//创建按钮点击方法
- (void)btnClick
{
//1.移动
//判断有没有在移动
if (!_isAnimating) {
//当不存在定时器时
if (_timer == nil) {
//创建
_timer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(updateTimer3) userInfo:nil repeats:YES];
}else{
//否则开始
[_timer setFireDate:[NSDate distantPast]];
}
//当在移动时
}else{
//暂停
[_timer setFireDate:[NSDate distantFuture]];
//设置单位矩阵,回到最开始的情况(回复初始状态)
_layer.transform = CATransform3DIdentity;
}
//取反_isAnimating
_isAnimating = !_isAnimating;
}