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?
UIImage contains the data for an image. UIImageView is a custom view meant to display the UIImage .
Deep copying UIImage *newImage = [UIImage imageWithData:UIImagePNGRepresentation(oldImage)]; This will copy the data but will require setting the orientation property before handing it to something like UIImageView for proper display. Another way to deep copy would be to draw into the context and grab the result.
For example: UIImage *img = [[UIImage alloc] init]; [img setImage:[UIImage imageNamed:@"anyImageName"]]; My UIImage object is declared in .
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!
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!)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With