views:

63

answers:

0

I open an UIImagePickerController where the user can see "through" his iPhone and position a (product) image on top of the camera view with different gestures. The position, size and rotation of the product image can change.

The user can then create a snapshot of the background image from the camera with the product image on top of it. Before iOS 4 I was just using UIGetScreenImage() to make a screenshot, but this is not allowed/possible anymore.

So now I actually make a picture with the UIImagePickerController and then try to position the product image on top of it again at the same location.

I tried this for hours now but don't get the results I want. It mostly works without rotation, but as soon as rotation comes into play it doesn't work anymore at all and the product is always positioned incorrectly.

Here's the code with some additional comments:



- (UIImage *)imageWithProductOverlay:(UIImage *)aBackgroundImage {
  CGSize  newBackgroundImageSize = aBackgroundImage.size; // size of the new image

  CGSize  oldBackgroundSize  = [[UIScreen mainScreen] applicationFrame].size; // the size of the old background image
  CGRect  oldProductRect     = [productView convertRect:productView.imageView.frame toView:nil]; // the rect of the product (updated with touch gestures by user)
  CGFloat oldProductRotation = atan2(productView.transform.b, productView.transform.a); // the rotation of the product (updated with touch gestures by user)

  UIGraphicsBeginImageContext(backgroundImageSize);
  CGContextRef context = UIGraphicsGetCurrentContext();

  [aBackgroundImage drawAtPoint:CGPointMake(0, 0)]; // draw the background image as the background

  // scale the context to the new larger dimensions
  CGContextScaleCTM(context, newBackgroundImageSize.width / oldBackgroundSize.width, newBackgroundImageSize.height / oldBackgroundSize.height);

  // move the origin of the product to the correct position in the new image
  CGContextTranslateCTM(context, oldProductRect.origin.x, oldProductRect.origin.y);

  // apply the same rotation to the new context as the old product image has it
  CGContextRotateCTM(context, oldProductRotation);

  // draw the image of the product onto the background at the same position
  // FIXME: this doesn't work when the old product is rotated
  CGRect newProductRect = CGRectMake(0, 0, oldProductRect.size.width, oldProductRect.size.height);
  [[currentProduct imageMedium] drawInRect:newProductRect];

  UIImage *imageWithProductOverlay = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();

  return imageWithProductOverlay;
}

How can I fix this so that the method returns a new larger image with the product positioned at exactly the same location?

Any help appreciated. Thanks.