2012-04-09 18 views
25

Tengo una aplicación de fotos donde puedes agregar pegatinas en una sección. Cuando hayas terminado, quiero guardar la imagen. Aquí está el código que tengo que hacer eso.Cómo recortar una imagen en iOS

if(UIGraphicsBeginImageContextWithOptions != NULL) 
{ 
    UIGraphicsBeginImageContextWithOptions(self.view.frame.size, YES, 2.5); 
} else { 
    UIGraphicsBeginImageContext(self.view.frame.size); 
} 
CGContextRef contextNew=UIGraphicsGetCurrentContext(); 

[self.view.layer renderInContext:contextNew]; 

UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 

UIGraphicsEndImageContext(); 

Ahora la imagen que es salvado es la pantalla completa de la imagen, lo cual está bien, pero ahora tengo que recortar la imagen y no sé cómo. Se puede ver la imagen en el siguiente enlace: http://dl.dropbox.com/u/19130454/Photo%202012-04-09%201%2036%2018%20PM.png

tengo que recortar: 91px desde la izquierda y la derecha 220px desde el fondo

Cualquier ayuda sería muy apreciada. Si no he explicado las cosas con claridad, házmelo saber y haré todo lo posible para volver a explicarlo.

+1

Esto podría ser una buena fuente para usted: [Open Source Biblioteca para agregar recortes de imágenes en una aplicación iOS rápidamente] (http://maniacdev.com/2011/10/open-source-library-to-add-image-cropping-into-an-ios-app-quickly/) – Lucien

+0

posible duplicado de [Image Cropping API para iOS] (http://stackoverflow.com/questions/7087435/image-cropping-api-for-ios) – NAlexN

Respuesta

34

¿Qué tal algo como esto

CGRect clippedRect = CGRectMake(self.view.frame.origin.x+91, self.view.frame.origin.y, self.view.frame.size.width-91*2, self.view.frame.size.height-220); 
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], clippedRect); 
UIImage *newImage = [UIImage imageWithCGImage:imageRef]; 
CGImageRelease(imageRef); 
+0

Muchas gracias por la ayuda. eso funcionó a la perfección! – flite3

+3

Esto ignora la orientación de la imagen porque UIImage lo admite, pero CGImage no – Dustin

1
- (UIImage*)imageByCropping:(CGRect)rect 
{ 
    //create a context to do our clipping in 
    UIGraphicsBeginImageContext(rect.size); 
    CGContextRef currentContext = UIGraphicsGetCurrentContext(); 

    //create a rect with the size we want to crop the image to 
    //the X and Y here are zero so we start at the beginning of our 
    //newly created context 
    CGRect clippedRect = CGRectMake(0, 0, rect.size.width, rect.size.height); 
    CGContextClipToRect(currentContext, clippedRect); 

    //create a rect equivalent to the full size of the image 
    //offset the rect by the X and Y we want to start the crop 
    //from in order to cut off anything before them 
    CGRect drawRect = CGRectMake(rect.origin.x * -1, 
           rect.origin.y * -1, 
           self.size.width, 
           self.size.height); 

    //draw the image to our clipped context using our offset rect 
    // CGContextDrawImage(currentContext, drawRect, self.CGImage); 
    [self drawInRect:drawRect]; // This will fix getting inverted image from context. 

    //pull the image from our cropped context 
    UIImage *cropped = UIGraphicsGetImageFromCurrentImageContext(); 

    //pop the context to get back to the default 
    UIGraphicsEndImageContext(); 

    //Note: this is autoreleased 
    return cropped; 
} 
+1

¿qué es self.CGImage? – Dvole

+1

Utilizando este método, mi imagen se recorta correctamente como se esperaba. Pero se invirtió automáticamente. ¿Puedes ayudarme con eso gracias? – iHulk

+0

@ user2534373 intente eliminar este UIGraphicsEndImageContext(); – Mohit

-1

Consulte el siguiente enlace cultivos de imágenes

https://github.com/myang-git/iOS-Image-Crop-View

** How to Use ** 

Very easy! It is created to be a drop-in component, so no static library, no extra dependencies. Just copy ImageCropView.h and ImageCropView.m to your project, and implement ImageCropViewControllerDelegate protocol. 
Use it like UIImagePicker: 
- (void)cropImage:(UIImage *)image{ 
    ImageCropViewController *controller = [[ImageCropViewController alloc] initWithImage:image]; 
    controller.delegate = self; 
    [[self navigationController] pushViewController:controller animated:YES]; 
} 
- (void)ImageCropViewController:(ImageCropViewController *)controller didFinishCroppingImage:(UIImage *)croppedImage{ 
    image = croppedImage; 
    imageView.image = croppedImage; 
    [[self navigationController] popViewControllerAnimated:YES]; 
} 
- (void)ImageCropViewControllerDidCancel:(ImageCropViewController *)controller{ 
    imageView.image = image; 
    [[self navigationController] popViewControllerAnimated:YES]; 
} 
+0

Agregue un contenido del enlace. – Robert

+0

hola mi propio ramani una ayuda .. mi imagen de recorte del proyecto como imagen de la forma de la cara también muchos tipos diferentes de cultivos de formas y cultivos mover y escalar para el objetivo c –

+0

utilizar esta demostración para cultivos de imágenes https://github.com/gavinbunney/Toucan –

2

para la siguiente código puede ayudarle.

Debe obtener el puño cropFrame correcta por el método de abajo

-(CGRect)cropRectForFrame:(CGRect)frame 
{ 
    // NSAssert(self.contentMode == UIViewContentModeScaleAspectFit, @"content mode must be aspect fit"); 

    CGFloat widthScale = imageview.superview.bounds.size.width/imageview.image.size.width; 
    CGFloat heightScale = imageview.superview.bounds.size.height/imageview.image.size.height; 

    float x, y, w, h, offset; 
    if (widthScale<heightScale) { 
     offset = (imageview.superview.bounds.size.height - (imageview.image.size.height*widthScale))/2; 
     x = frame.origin.x/widthScale; 
     y = (frame.origin.y-offset)/widthScale; 
     w = frame.size.width/widthScale; 
     h = frame.size.height/widthScale; 
    } else { 
     offset = (imageview.superview.bounds.size.width - (imageview.image.size.width*heightScale))/2; 
     x = (frame.origin.x-offset)/heightScale; 
     y = frame.origin.y/heightScale; 
     w = frame.size.width/heightScale; 
     h = frame.size.height/heightScale; 
    } 
    return CGRectMake(x, y, w, h); 
} 

Luego hay que llamar a este método para obtener la imagen recortada

- (UIImage *)imageByCropping:(UIImage *)image toRect:(CGRect)rect 
{ 
    // you need to update scaling factor value if deice is not retina display 
    UIGraphicsBeginImageContextWithOptions(rect.size, 
              /* your view opaque */ NO, 
              /* scaling factor */ 2.0); 

    // stick to methods on UIImage so that orientation etc. are automatically 
    // dealt with for us 
    [image drawAtPoint:CGPointMake(-rect.origin.x, -rect.origin.y)]; 

    UIImage *result = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 

    return result; 
} 
Cuestiones relacionadas