For me, I need to utilize both functions: AVMakeRectWithAspectRatioInsideRect & CGImageCreateWithImageInRect to get the desired results. My problem was the aspect ratio difference between my mainImage and the drawImage. So AVMakeRectWithAspectRatioInsideRect gave me a new rectangle with the correct size ratio and origin points for my mainImage. After that, I used CGImageCreateWithImageInRect to lay the [drawImage CGImage] into the new rectangle and Presto! My drawImage and mainImage create a new context with the exact same aspect ratio. No more distortion or skewing of images. Working code is posted below.
- (void) commitDrawingWithOpacity:(CGFloat)opacity {
CGRect drawRect = AVMakeRectWithAspectRatioInsideRect(mainImage.size, self.frame);
UIGraphicsBeginImageContext(mainImage.size);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextScaleCTM(ctx, 1.0f, -1.0f);
CGContextTranslateCTM(ctx, 0.0f, -mainImage.size.height);
CGRect rect = CGRectMake(0.0f, 0.0f, mainImage.size.width, mainImage.size.height);
if (mainImage != nil) {
CGContextDrawImage(ctx, rect, mainImage.CGImage);
}
CGImageRef imageRef = CGImageCreateWithImageInRect([drawImage CGImage], drawRect);
CGContextSetAlpha(ctx, opacity);
CGContextDrawImage(ctx, rect, imageRef);
mainImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.layer.contents = (id)mainImage.CGImage;
drawLayer.contents = nil;
drawImage = nil;
}