Perspective and Flipping an UIImageView At The Same Time
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
);
I was able to accomplish this effect in 4 (optionally 5) steps:
- Create two UIImageViews in your nib. Create a UIImageView for your main image, then another for your reflected image. Make sure their view content modes are both set to Aspect Fit. Also, make the frame size of the reflected image 2x that of your main image (because the perspective reflection will add width to the image).
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:
精彩评论