Question

I have a layer that I need to transform. Currently I am using the following:

self.customLayer.transform = CATransform3DRotate(CATransform3DIdentity,M_PI / 2.0f, 0, 0, 1);

This correctly makes the layer right side up, but it also needs to be flipped horizontally, since it is the wrong way. How can I adjust CATransform3DRotate to do this?

Was it helpful?

Solution

You'll need:

self.customLayer.transform = CATransform3DScale(CATransform3DMakeRotation(M_PI / 2.0f, 0, 0, 1),
                                                -1, 1, 1);

A scale with -1 is a flip. Imagine you're squashing the image horizontally and you go past zero.

OTHER TIPS

Since the parameter here is

CATransform3DScale (CATransform3D t, CGFloat sx, CGFloat sy, CGFloat sz)

If you want to flip horizontally, you should not provide any vector value in CATransform3DMakeRotation(). Instead, you want to just control the scale of x-axis.

By flipping it horizontally you should:

self.transform = CATransform3DScale(CATransform3DMakeRotation(0, 0, 0, 0),
                                        -1, 1, 1);

If you want to flip it back to origin, you do:

self.transform = CATransform3DScale(CATransform3DMakeRotation(0, 0, 0, 0),
                                        1, 1, 1);  

Addition:
A shorter version will save you one operation. To flip:

self.transform = CATransform3DMakeRotation(M_PI, 0, 1, 0);

To flip back to normal:

self.transform = CATransform3DMakeRotation(0, 0, 1, 0);

I personally find it better readable to use KVC for these things. You could probably use something like the following to achieve the same effect:

// Rotate the layer 90 degrees to the left
[self.customLayer setValue:@-1.5707 forKeyPath:@"transform.rotation"];
// Flip the layer horizontally
[self.customLayer setValue:@-1 forKeyPath:@"transform.scale.x"];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top