9

I am trying to use CGImageCreateWithImageInRect to get a sub-image from an image but it's not working properly. It returns the image from a random place in the image, rather than the one I specify. Please take a look at the following image;

enter image description here

My code is:

CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], CGRectMake(524, 1331, 600, 600));
UIImage *croppedImage = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);

But that doesn't work. What am I doing wrong?

Thanks!

0xSina
  • 20,973
  • 34
  • 136
  • 253

2 Answers2

6

It is likely that your image has a UIImageOrientation set for it that is different from what you are expecting. The iOS will display the image properly, yet the image will be stored sideways (for lack of a better term).

So when you say give me the rect starting at x, y you will get y, x instead, or some random craziness because you are accessing a rect that is outside of the normal range.

This answer talks about fixing the orientation.

Community
  • 1
  • 1
HalR
  • 11,411
  • 5
  • 48
  • 80
2

please see followed answer, you need transform the rect or transform the image. I prefer to transforming the rect.

https://stackoverflow.com/a/21560825/2482283

Community
  • 1
  • 1
andrewchan2022
  • 4,953
  • 45
  • 48