-
CATransformLayer 3D渲染层
CATransformLayer是一个用来渲染3d模型的层,显示的是3维空间,不同于2维平面,所以会忽略filters, backgroundFilters, compositingFilter, mask, masksToBounds, shadow等2维平面的属性,并且也不会调用hitTest:方法。
设备:xcode 10.1
语言:swift 4.2
我们在CATransformLayer上建立子层用来显示3d动画。我们先来看下效果。
整体思路:
创建一个CATransformLayer为containLayer,并且设M34做深景模式,然后在containLayer上面添加6个面,对成一个立体图,然后旋转containLayer。
代码实现:
定义一个 CATransformLayer
var containLayer: CATransformLayer!
创建一个CATransformLayer
containLayer = CATransformLayer();
containLayer.backgroundColor = UIColor.green.cgColor;
containLayer.frame = sRect;
view.layer.addSublayer(containLayer);
containLayer.position = self.view.center;
创建6个面,组成一个立体形状:
func createSubLayer() -> Void {
var tranfrom = CATransform3DMakeTranslation(0, 0, sRect.width/2);
addSubLayerTo(trans: tranfrom,index: 1);
tranfrom = CATransform3DMakeTranslation(0, 0, -sRect.width/2);
addSubLayerTo(trans: tranfrom, index: 2);
tranfrom = CATransform3DMakeTranslation(0, sRect.height/2,0);
tranfrom = CATransform3DRotate(tranfrom, .pi/2, 1, 0, 0);
addSubLayerTo(trans: tranfrom, index: 3);
tranfrom = CATransform3DMakeTranslation(0, -sRect.height/2, 0);
tranfrom = CATransform3DRotate(tranfrom, .pi/2, 1, 0, 0);
addSubLayerTo(trans: tranfrom, index: 4);
tranfrom = CATransform3DMakeTranslation(sRect.width/2, 0, 0);
tranfrom = CATransform3DRotate(tranfrom, .pi/2, 0, 1, 0);
addSubLayerTo(trans: tranfrom, index: 5);
tranfrom = CATransform3DMakeTranslation(-sRect.width/2, 0, 0);
tranfrom = CATransform3DRotate(tranfrom, .pi/2, 0, 1, 0);
addSubLayerTo(trans: tranfrom, index: 6);
}
func addSubLayerTo(trans: CATransform3D,index: Int) -> Void {
let layer = CATextLayer();
layer.frame = .init(x: 0, y: 0, width: sRect.width, height: sRect.height);
containLayer?.addSublayer(layer);
layer.transform = trans;
layer.backgroundColor = UIColor.random.cgColor;
layer.string = "\(index)";
layer.alignmentMode = .center;
layer.contentsGravity = .center;
layer.fontSize = 40;
layer.foregroundColor = UIColor.random.cgColor;
}
运行动画:
func runAnimation() -> Void {
var frame = CATransform3DIdentity;
frame.m34 = -1.0/500.0;
frame = CATransform3DRotate(frame, degree, 0, 1, 0);
degree += .pi * 1.1
var toend = CATransform3DIdentity;
toend.m34 = -1.0/500;
toend = CATransform3DRotate(toend, degree, 1, 1, 1);
let transform3d = CABasicAnimation(keyPath: "transform");
transform3d.duration = 5;
transform3d.fromValue = frame;
transform3d.toValue = toend;
transform3d.repeatCount = 100;
transform3d.fillMode = .forwards;
transform3d.isAdditive = true;
transform3d.autoreverses = true;
containLayer?.add(transform3d, forKey: "transform3d");
}