Apply CATransform3D on UIImage while drawing on context

844 views Asked by At

I've several UIImageView and applied CATransform3D on its layer property and now I want to get a single image (combine all images in to one with transformation).

For that I'm using CoreGraphics framework to draw an image on context and then get resultant image.

Need to achieve this:

  • Draw each image on context with CATransform3D and then get an image from the image context.

I've tried this but didn't get succeed.

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextConcatCTM(context, CATransform3DGetAffineTransform(imageView.layer.transform));
CGContextDrawImage(context, (CGRect){ CGPointZero, imageView.image.size }, [imageView.image CGImage]);
CGContextTranslateCTM(context, 0, imageView.frame.size.height);
CGContextScaleCTM(context, 1.0, -1.0);

UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();

I have also tried CoreImage framework but still no luck. :(

CIImage *ciImage = [CIImage imageWithData:UIImagePNGRepresentation(imageView.image)];
CIContext *context = [CIContext contextWithOptions:nil];
CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeRectangle context:context options:@{CIDetectorAccuracy: CIDetectorAccuracyHigh}];

CIRectangleFeature *rect = (CIRectangleFeature *)[detector featuresInImage:ciImage options:@{CIDetectorImageOrientation : [NSNumber numberWithInt:1]}].firstObject;

CIFilter *filterMain = [CIFilter filterWithName:@"CIPerspectiveCorrection"];
[filterMain setValue:[CIVector vectorWithCGPoint:rect.topLeft] forKey:@"inputTopLeft"];
[filterMain setValue:[CIVector vectorWithCGPoint:rect.topRight] forKey:@"inputTopRight"];
[filterMain setValue:[CIVector vectorWithCGPoint:rect.bottomRight] forKey:@"inputBottomRight"];
[filterMain setValue:[CIVector vectorWithCGPoint:rect.bottomLeft] forKey:@"inputBottomLeft"];
[filterMain setValue:sourceCIImage forKey:kCIInputImageKey];

CIImage *outputImage = [filterMain valueForKey:kCIOutputImageKey];
UIImage *resultImage = [UIImage imageWithCIImage:outputImage];

The about line of code gives me some weird results.

The other thing that I've tried is drawViewHierarchyInRect:afterScreenUpdates: method but it gives me very blur image.

So how can I achieve drawing an image on context with CATransform3D ? if someone have faced this kind of issue and fixed it, please share your thoughts. Any help will be appreciated.

NOTE: I'm not talking about CGAffineTransformation its CATransform3D

1

There are 1 answers

0
Mahendra On BEST ANSWER

Apple have provided a framework called CoreImage, you can get transformed image by applying filters. You can use CIPerspectiveTransform filter to get transformed image by passing four corners of image/imageview (TopLeft, TopRight, BottomLeft and BottomRight).

I've answered this kind of question here...