I have a UIImage which contains a shape; the rest is transparent. I’d like to get another UIImage by cropping out as much of the transparent part as possible, still retaining all of the non-transparent pixels – similar to the autocrop function in GIMP. How would I go about doing this?
Share
This approach may be a little more invasive than what you were hoping for, but it gets the job done. What I’m doing is creating a bitmap context for the UIImage, obtaining a pointer to the raw image data, then sifting through it looking for non-transparent pixels. My method returns a CGRect which I use to create a new UIImage.
The method to create the Bitmap Context:
And finally, get your new cropped UIImage from the returned CGRect:
I grabbed a bit of that code from this very useful article. Hope it helps!