15

I want to grab a subimage from a UIImage. I've looked around for a similar question, to no avail.

I know the range of pixels I want to grab - how can I return this subimage, from an existing image?

3 Answers 3

28

This should help: http://iphonedevelopment.blogspot.com/2010/11/drawing-part-of-uiimage.html

This code snippet is creating a category of UIImage but the code should be easily modified to work without it being a category.

A shorter way of doing the same thing is the following:

CGRect fromRect = CGRectMake(0, 0, 320, 480); // or whatever rectangle CGImageRef drawImage = CGImageCreateWithImageInRect(image.CGImage, fromRect); UIImage *newImage = [UIImage imageWithCGImage:drawImage]; CGImageRelease(drawImage); 

Hope this helps!

Sign up to request clarification or add additional context in comments.

3 Comments

This way should run under main thread, it is not a thread-safe method.
This won't work for retina devices, as it'll cut the raw image and not the representation in the retina screen (i.e. if 320x480 is the normal and 640x960 the retina resolution of the original image, the CGRect with (0, 0, 320, 480) would cut out the upper left quarter of the image when on retina)
@ohcibi To make this coed also work with retina, you need to get the scale factor of the image (image.scale), apply it to the rect (multiply all numeric values by that factor) and when creating the final UIImage, use the method imageWithCGImage:scale:orientation: to set the correct scale factor again.
5

Updated @donkim answer for swift 3:

 let fromRect=CGRect(x:0,y:0,width:320,height:480) let drawImage = image.cgImage!.cropping(to: fromRect) let bimage = UIImage(cgImage: drawImage!) 

Comments

1

In Swift 4, taking into account screen scale (otherwise your new image will be too large):

 let img = UIImage(named: "existingImage")! let scale = UIScreen.main.scale let dy: CGFloat = 6 * scale // say you want 6pt from bottom let area = CGRect(x: 0, y: img.size.height * scale - dy, width: img.size.width * scale, height: dy) let crop = img.cgImage!.cropping(to: area)! let subImage = UIImage(cgImage: crop, scale: scale, orientation:.up) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.