Graphics Reference
In-Depth Information
So, let's try it using a
CATransformLayer
instead. The first problem to address is that
we constructed our cube in Chapter 5 using views rather than standalone layers. We cannot
place a view-backing layer inside another layer that is not itself a view-backing layer
without messing up the view hierarchy. We could create a new
UIView
subclass backed
by a
CATransformLayer
(using the +
layerClass
method), but to keep things simple
for our example, let's just re-create the cube using standalone layers instead of views. This
means we can't display buttons and labels on our cube faces like we did in Chapter 5, but
we don't need to do that right now.
Listing 6.5 contains the code. We position each cube face using the same basic logic we
used in Chapter 5. But instead of adding the cube faces directly to the container view's
backing layer as we did before, we place them inside a
CATransformLayer
to create a
standalone cube object, and then place two such cubes into our container. We've colored
the cube faces randomly so as to make it easier to distinguish them without labels or
lighting. Figure 6.5 shows the result.
Listing 6.5
Assembling a 3D Layer Hierarchy Using
CATransformLayer
@interface
ViewController ()
@property
(
nonatomic
,
weak
)
IBOutlet
UIView
*containerView;
@end
@implementation
ViewController
- (
CALayer
*)faceWithTransform:(
CATransform3D
)transform
{
//create cube face layer
CALayer
*face = [
CALayer
layer
];
face.
frame
=
CGRectMake
(-
50
, -
50
,
100
,
100
);
//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
;
//apply the transform and return
face.
transform
= transform;
return
face;
}