It seems simple enough. I have a UIImageView which I apply an arbitrary CGAffineTransform to, but now I want to get a cropped portion of the transformed image.
Here is the code I'm currently using:
Code:
// Begin the drawing
UIGraphicsBeginImageContext(cropRect.size);
CGContextRef ctx = UIGraphicsGetCurrentContext();
// Clear whole thing
CGContextClearRect(ctx, CGRectMake(0, 0, cropRect.size.width, cropRect.size.height));
// Transform the image (as the image view has been transformed)
CGContextConcatCTM(ctx, imageView.transform);
// Translate to compensate for the different positions of the image
CGContextTranslateCTM(ctx, -((imageView.bounds.size.width*0.5)-(cropRect.size.width*0.5)),
(imageView.bounds.size.height*0.5)-(cropRect.size.height*0.5));
// Tanslate and scale upside-down to compensate for Quartz's inverted coordinate system
CGContextTranslateCTM(ctx, 0.0, maskRect.size.height);
CGContextScaleCTM(ctx, 1.0, -1.0);
// Draw view into context
CGContextDrawImage(ctx, imageViewbounds, imageView.image.CGImage);
// Create the new UIImage from the context
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
// End the drawing
UIGraphicsEndImageContext();
So far this works great, as long as my transform is limited to translations. If the transform involves any scaling or rotating, then the image resulting from the crop is at a different location than I intended. I've been struggling to get my head around this problem for ages now, so I would really appreciate any kind of input on the matter.
Thanks.