CATransformLayer不同于普通的CALayer锡凝,因?yàn)樗荒茱@示她自己的內(nèi)容,只有當(dāng)存在了一個(gè)能作用域子圖層的變換它才真正存在灭返。CATransformLayer并不平面化它的子圖層,所以它能夠用于構(gòu)造一個(gè)層級(jí)的3D結(jié)構(gòu)。
下面我們代碼演示CATransformLayer的基本使用铅辞,創(chuàng)建立方體放置在一個(gè)CATransformLayer中,然后將兩個(gè)這樣的立方體放進(jìn)容器中萨醒。
<pre>import UIKit
class ViewController: UIViewController {
var containerView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
self.containerView = UIView()
self.containerView.frame = self.view.bounds
self.containerView.backgroundColor = UIColor.groupTableViewBackground
self.view.addSubview(self.containerView)
var pt = CATransform3DIdentity
pt.m34 = -1.0 / 500.0
self.containerView.layer.sublayerTransform = pt
var c1t = CATransform3DIdentity
c1t = CATransform3DTranslate(c1t, -100, 0, 0)
let cube1 = self.cubeWithTransform(transform: c1t)
self.containerView.layer.addSublayer(cube1)
var c2t = CATransform3DIdentity
c2t = CATransform3DTranslate(c2t, 100, 0, 0)
c2t = CATransform3DRotate(c2t, -(CGFloat)(M_PI_4), 1, 0, 0)
c2t = CATransform3DRotate(c2t, -(CGFloat)(M_PI_4), 0, 1, 0)
let cube2 = self.cubeWithTransform(transform: c2t)
self.containerView.layer.addSublayer(cube2)
}
func faceWithTransform(transform: CATransform3D) -> CALayer
{
let face = CALayer()
face.frame = CGRect(x: -50, y: -50, width: 100, height: 100)
let red = arc4random() % 256
let green = arc4random() % 256
let blue = arc4random() % 256
face.backgroundColor = UIColor(red: CGFloat(red) / 255, green: CGFloat(green) / 255, blue: CGFloat(blue) / 255, alpha: 1).cgColor
face.transform = transform
return face
}
func cubeWithTransform(transform: CATransform3D) -> CALayer
{
let cube = CATransformLayer()
// 1
var ct = CATransform3DMakeTranslation(0, 0, 50)
cube.addSublayer(self.faceWithTransform(transform: ct))
// 2
ct = CATransform3DMakeTranslation(50, 0, 0)
ct = CATransform3DRotate(ct, CGFloat(M_PI_2), 0, 1, 0)
cube.addSublayer(self.faceWithTransform(transform: ct))
// 3
ct = CATransform3DMakeTranslation(0, -50, 0)
ct = CATransform3DRotate(ct, CGFloat(M_PI_2), 1, 0, 0)
cube.addSublayer(self.faceWithTransform(transform: ct))
// 4
ct = CATransform3DMakeTranslation(0, 50, 0)
ct = CATransform3DRotate(ct, CGFloat(-M_PI_2), 1, 0, 0)
cube.addSublayer(self.faceWithTransform(transform: ct))
// 5
ct = CATransform3DMakeTranslation(-50, 0, 0)
ct = CATransform3DRotate(ct, CGFloat(-M_PI_2), 0, 1, 0)
cube.addSublayer(self.faceWithTransform(transform: ct))
// 6
ct = CATransform3DMakeTranslation(0, 0, -50)
ct = CATransform3DRotate(ct, CGFloat(M_PI), 0, 1, 0)
cube.addSublayer(self.faceWithTransform(transform: ct))
let containerSize = self.containerView.bounds.size
cube.position = CGPoint(x: containerSize.width / 2, y: containerSize.height / 2)
cube.transform = transform
return cube
}
}
</pre>