Reputation: 11
I am trying to flip and give perspective rotate an uiimageview, in order to obtain an effect like reflection. first i give perspective using CATransform3D and then flip using CGAffineTransformMake. However i loose the perspective effect after the second trasnformation. and i couldn't figure out how to perspective and flip both using CATransform3D. img is the first image and img2 will be its reflection.
CALayer *layer = img.layer;
CATransform3D rotationAndPerspectiveTransform = CATransform3DIdentity;
rotationAndPerspectiveTransform.m34 = 1.0 / -600;
rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, 30.0f * M_PI / 180.0f, 0.0f, 1.0f, 0.0f);
layer.transform = rotationAndPerspectiveTransform;
img2.transform = CGAffineTransformMake(
1, 0, 0, -1, 0, img2.bounds.size.height
);
Upvotes: 1
Views: 802
Reputation: 17081
I was able to accomplish this effect in 4 (optionally 5) steps:
Load up the main image as normal. Now load up the reflection to be upside-down like so:
reflectionView.image = [UIImage
imageWithCGImage:mainImageView.image.CGImage
scale:1.0f
orientation: UIImageOrientationDownMirrored];
Now create the perspective transform like so:
CATransform3D rotationAndPerspectiveTransform = CATransform3DIdentity;
rotationAndPerspectiveTransform.m24 = 1.0f/-mainImageView.frame.size.width;
[[reflectionView layer] setTransform:rotationAndPerspectiveTransform];
Finally, move the reflection into place:
reflectionView.center = CGPointMake(self.view.frame.size.width/2, mainImageView.frame.size.height*1.5);
Optionally, add a gradient to make the reflection fade away into the background:
reflectionView.layer.masksToBounds = YES;
// define gradient
CAGradientLayer *theGradient = [CAGradientLayer layer];
theGradient.frame = reflectionView;
theGradient.colors = [NSArray arrayWithObjects:
(id)[[UIColor clearColor] CGColor],
(id)[[UIColor blackColor] CGColor], nil];
// add gradient to reflection image
[reflectionView insertSublayer:theGradient atIndex:0];
reflectionView = 0.25f;
It looks like this:
Upvotes: 2