Question

I am using CGImageCreateWithImageInRect to crop an image take with the camera. The orientation of the iPhone (and the photo image) is Portrait and my understanding is that CGImageCreateWithImageInRect expects the origin to be in the lower left corner of the phone, when holding it in Portrait. In other words, the origin should start at coordinate 0,480 and y increments as you go up towards the top left corner, and x stays the same.

However, to my surprise, it is the x coordinate that I had to move, in order for the following code to work properly. The x origin had to start at the top right corner,with y remaining unchanged. Looking at other usages of CGImageCreateWithImageInRect online and here on SO, I don't see any code to mitigate the issue I am having so I am stumped as to why the following code only works when the origin is moved to from 0,0 to 320,0.

Can anyone add some insight? Thanks!

- (UIImage *)crop:(CGRect)rect {
    CGImageRef croppedImageRef = CGImageCreateWithImageInRect([self CGImage], CGRectMake(rect.origin.y, [self size].width - rect.origin.x - rect.size.width, rect.size.height, rect.size.width));
    UIImage *croppedImage = [UIImage imageWithCGImage:croppedImageRef scale:self.scale orientation:[self imageOrientation]]; 
    CGImageRelease(croppedImageRef);
    return croppedImage;

}

Was it helpful?

Solution

I think this answers my own question:

From the AV Foundation guide:

You pass a CGPoint where {0,0} represents the top left of the picture area, and {1,1} represents the bottom right in landscape mode with the home button on the right—this applies even if the device is in portrait mode.

So for all images from the camera, it seems that the origin (x=0, y=0) is at the top right of portrait-left orientation, which for Core Graphics, translates to (y, -x).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top