Cory
Cory

Reputation: 2312

Understanding perspective transform in 3D Core Animation

I’m trying to create a view consisting of several 3D cube’s viewed from a center perspective of the containing view.

When I set a cube view as a direct subview of the container view and then set the perspective as follows;

var perspective = CATransform3DIdentity
perspective.m34 = -1.0/250
containerView.layer.sublayerTransform = perspective

The 3d perspective transform works as expected. However, if I first add the cube view to a innerContainerView and then add that to the parent container view the perspective is lost. I created a playground to illustrate my problem.

let containerView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 667.0, height: 375.0))
containerView.backgroundColor = UIColor.grayColor()
XCPlaygroundPage.currentPage.liveView = containerView

let green = UIColor.greenColor()
let blue = UIColor.blueColor()
let red = UIColor.redColor()
let purple = UIColor.purpleColor()
let yellow = UIColor.yellowColor()
let orange = UIColor.orangeColor()


var perspective = CATransform3DIdentity
perspective.m34 = -1.0/250
containerView.layer.sublayerTransform = perspective

let cubeView1 = CubeView(frontColor: green, backColor: blue, topColor: red, rightColor: purple, bottomColor: yellow, leftColor: orange)
cubeView1.frame = CGRectMake(50, 50, 100, 100)
let innerContainerView = UIView(frame: CGRectMake(0, 100, 200, 200))
innerContainerView.backgroundColor = UIColor.lightGrayColor()
containerView.addSubview(innerContainerView)
innerContainerView.addSubview(cubeView1)


let cubeView2 = CubeView(frontColor: green, backColor: blue, topColor: red, rightColor: purple, bottomColor: yellow, leftColor: orange)
cubeView2.frame = CGRectMake(400, 200, 100, 100)
containerView.addSubview(cubeView2)

Playground image

I'm trying to create the same perspective shown in the right cube in the left cube. So why is it when I add the an intermediate view I lose the perspective?

Upvotes: 1

Views: 361

Answers (1)

Bartosz Ciechanowski
Bartosz Ciechanowski

Reputation: 10333

CoreAnimaton rendering model always flattens rendering operations on to the parent layer. The one exception to this rule is CATransformLayer which doesn't do any flattening and just passes the transforms through. Creating a UIView with CATransformLayer as the layerClass and using that as innerContainerView should solve the issue.

Upvotes: 2

Related Questions