1

Crop image from particular position and set to another view

Final image view

self.finalImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 20, 320, 320)];
if(rectangle_button_preesed_view)
{
    self.finalImageView.image =[self croppIngimageByImageName:self.imageView.image toRect:CGRectMake(30, 120, 260, 340)];
}
else
{
    self.finalImageView.image =[self croppIngimageByImageName:self.imageView.image toRect:CGRectMake(30, 80, 260, 260)];
}

Cropping image

- (UIImage *)croppIngimageByImageName:(UIImage *)imageToCrop toRect:(CGRect)rect
{
    CGImageRef imageRef = CGImageCreateWithImageInRect([imageToCrop CGImage], rect);
    UIImage *cropped = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);
    NSLog(@" cropped size %f %f ",cropped.size.width,cropped.size.height);
    return cropped;    
}
Mehmet Emre Portakal
  • 1,774
  • 21
  • 37

3 Answers3

0
CGImageRef imageRef = CGImageCreateWithImageInRect([largeImage CGImage], cropRect);
// or use the UIImage wherever you like
[UIImageView setImage:[UIImage imageWithCGImage:imageRef]]; 
CGImageRelease(imageRef);

OR

@implementation UIImage (Crop)

- (UIImage *)crop:(CGRect)rect {

    rect = CGRectMake(rect.origin.x*self.scale, 
                      rect.origin.y*self.scale, 
                      rect.size.width*self.scale, 
                      rect.size.height*self.scale);       

    CGImageRef imageRef = CGImageCreateWithImageInRect([self CGImage], rect);
    UIImage *result = [UIImage imageWithCGImage:imageRef 
                                          scale:self.scale 
                                    orientation:self.imageOrientation]; 
    CGImageRelease(imageRef);
    return result;
}

@end
Erhan
  • 908
  • 8
  • 19
0

Beside CoreGraphics solution, I would also suggest to use CoreImage which support filters for image manipulation. You should look at CICrop filter found in this documentation page.

Note: This filter is supported for iOS 5 or greater.

I currently do not have an exact solution but you can go ahead with a similar thread.

Hope it helps!

Community
  • 1
  • 1
NeverHopeless
  • 11,077
  • 4
  • 35
  • 56
0
@implementation UIImage (Crop)

- (UIImage *)crop:(CGRect)cropRect {

    CGImageRef imageRef = CGImageCreateWithImageInRect([self CGImage], cropRect);
    UIImage *cropedImage = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);

    return cropedImage;

}
holex
  • 23,961
  • 7
  • 62
  • 76
Maksim Usenko
  • 311
  • 3
  • 5