使用CATransformLayer制作3D图像和动画

之前我们讲过可以用CALayer搭配CATransform3D来实现将View做3D旋转, 今天我们再看一个3D的新东西

CATransformLayer, 看名字就知道这个layer跟旋转有关, 那么具体是什么呢?

我们看他的头文件, 没有任何属性. 他其实是作为一个容器, 我们可以往里面添加其他的CALayer

比如我们要创建一个3D效果的立方体,

使用CATransformLayer制作3D图像和动画

可以先创建一个CATransformlayer容器,

正方体的6个面我们以3D旋转后的Layer表示, 加入到容器中, 调整好每个面的角度和位置让他们拼接再一起就是一个正方体了

我们上代码吧

- (void)viewDidLoad {

    [super viewDidLoad];

    //create cube layer
CATransformLayer *cube = [CATransformLayer layer]; //add cube face 1
CATransform3D ct = CATransform3DMakeTranslation(, , );
[cube addSublayer:[self faceWithTransform:ct]]; //add cube face 2
ct = CATransform3DMakeTranslation(, , );
ct = CATransform3DRotate(ct, M_PI_2, , , );
[cube addSublayer:[self faceWithTransform:ct]]; //add cube face 3
ct = CATransform3DMakeTranslation(, -, );
ct = CATransform3DRotate(ct, M_PI_2, , , );
[cube addSublayer:[self faceWithTransform:ct]]; //add cube face 4
ct = CATransform3DMakeTranslation(, , );
ct = CATransform3DRotate(ct, -M_PI_2, , , );
[cube addSublayer:[self faceWithTransform:ct]]; //add cube face 5
ct = CATransform3DMakeTranslation(-, , );
ct = CATransform3DRotate(ct, -M_PI_2, , , );
[cube addSublayer:[self faceWithTransform:ct]]; //add cube face 6
ct = CATransform3DMakeTranslation(, , -);
ct = CATransform3DRotate(ct, M_PI, , , );
[cube addSublayer:[self faceWithTransform:ct]]; //center the cube layer within the container
CGSize containerSize = self.view.bounds.size;
cube.position = CGPointMake(containerSize.width / 2.0, containerSize.height / 2.0); cube.transform = CATransform3DMakeRotation(, , , ); [self.view.layer addSublayer:cube];
} - (CALayer *)faceWithTransform:(CATransform3D)transform
{
//create cube face layer
CALayer *face = [CALayer layer];
face.bounds = CGRectMake(, , , );
//apply a random color
CGFloat red = (rand() / (double)INT_MAX);
CGFloat green = (rand() / (double)INT_MAX);
CGFloat blue = (rand() / (double)INT_MAX);
face.backgroundColor = [UIColor colorWithRed:red green:green blue:blue alpha:1.0].CGColor;
face.transform = transform;
return face;
}
@end

我们可以再给容器一个旋转动画, 就实现了一个旋转的立方体

CATransform3D transA = CATransform3DMakeRotation(, , , );

    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform"];
animation.duration = ;
animation.autoreverses = YES;
animation.repeatCount = ;
animation.toValue = [NSValue valueWithCATransform3D:transA];
[cube addAnimation:animation forKey:nil];
上一篇:[c#基础]使用抽象工厂实现三层 和反射


下一篇:nodejs 监听文件夹变化的模块