Cropping an UIImage

I’ve got some code that resizes an image so I can get a scaled chunk of the center of the image – I use this to take a UIImage and return a small, square representation of an image, similar to what’s seen in the album view of the Photos app. (I know I could use a UIImageView and adjust the crop mode to achieve the same results, but these images are sometimes displayed in UIWebViews).

I’ve started to notice some crashes in this code and I’m a bit stumped. I’ve got two different theories and I’m wondering if either is on-base.

Theory 1) I achieve the cropping by drawing into an offscreen image context of my target size. Since I want the center portion of the image, I set the CGRect argument passed to drawInRect to something that’s larger than the bounds of my image context. I was hoping this was Kosher, but am I instead attempting to draw over other memory that I shouldn’t be touching?

Theory 2) I’m doing all of this in a background thread. I know there are portions of UIKit that are restricted to the main thread. I was assuming / hoping that drawing to an offscreen view wasn’t one of these. Am I wrong?

(Oh, how I miss NSImage's drawInRect:fromRect:operation:fraction: method.)

25 Answers
25

Leave a Comment