Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to crop a UIImageView to a new UIImage in 'aspect fit' mode?
    primarykey
    data
    text
    <p><img src="https://i.stack.imgur.com/6X1L1.png" alt="enter image description here"></p> <p>I would like to create a new UIImage by cropping the image inside a UIImageView. For example in the above pic, I want a new UIImage of the area outlined in green. I found code to do this, normally it looks something like this (as a UIImage category):</p> <pre><code>- (UIImage *)croppedImage:(CGRect)bounds { CGImageRef imageRef = CGImageCreateWithImageInRect([self CGImage], bounds); UIImage *croppedImage = [UIImage imageWithCGImage:imageRef]; CGImageRelease(imageRef); return croppedImage; } </code></pre> <p>Makes perfect sense. HOWEVER, my UIImageView is in contentMode 'aspect fit'. Seems like that complicates the CGRect calculations for CGImageCreateWithImageInRect and I haven't been able to figure out the right solution. </p> <p>I figure I need to apply the same transformations to the green rect as were done to the image? </p> <p>ALSO: I found this other question here (<a href="https://stackoverflow.com/questions/6278876/how-to-know-the-image-size-after-applying-aspect-fit-for-the-image-in-an-uiimage">How to know the image size after applying aspect fit for the image in an UIImageView</a>), which seems to show a brute force way of getting the size, but I am still not sure how that fits into a cropping situation.</p> <p>Any ideas?</p> <p><strong>EDIT</strong>: In my case, I literally have a square as shown above drawn in an overlay view over the UIImageView. So while I realize I am cropping the UIImage (inside the UIImageView), I need to somehow change the green CGRect such that it 'matches' the transformation done when 'aspect fit' is applied. For example, if I leave my UIImageView in 'top left' mode, then everything works fine, because there is a 1:1 mapping between the underlying UIImage and the UIImageView. The problem in 'top left' mode is that the entire image doesn't always display, because it might be bigger than my UIImageView.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload