2010-10-17 17 views
16

por lo que actualmente estoy tratando de recortar y cambiar el tamaño de una imagen para que quepa en un tamaño específico sin perder la proporción.cambiar el tamaño y recortar la imagen centrada

una imagen pequeña para mostrar lo que quiero decir:

alt text

he jugado un poco con vocaro's categories pero no funcionan con la png y tienen problemas con gifs. también la imagen no se recorta.

¿Alguien tiene alguna sugerencia de cómo hacer este cambio de tamaño de la mejor manera o probablemente tenga un enlace a una biblioteca/categoría/lo que sea?

gracias por todos los consejos!

p.s .: hace ios implementar un "seleccionar un extracto" para que tenga la proporción correcta y solo tenga que escalarlo?

+0

+1 Choise, necesito tu ayuda ahora. Si tienes la respuesta significa que pls Publicar la respuesta, Bcoz necesito lo mismo yar ** Pls ** !! –

+0

+1 Para una presentación detallada – shashwat

Respuesta

7

Este método hará lo que quiera y es una categoría de UIImage por su facilidad de uso. Fui con el tamaño y luego recortar, podría cambiar el código con bastante facilidad si desea recortar y luego cambiar el tamaño. La verificación de límites en la función es puramente ilustrativa. Es posible que desee hacer algo diferente, por ejemplo, centrar el recorte en relación con las dimensiones de la imagen de salida, pero esto debería acercarlo lo suficiente como para realizar cualquier otro cambio que necesite.

@implementation UIImage(resizeAndCropExample) 

- (UIImage *) resizeToSize:(CGSize) newSize thenCropWithRect:(CGRect) cropRect { 
    CGContextRef    context; 
    CGImageRef     imageRef; 
    CGSize      inputSize; 
    UIImage      *outputImage = nil; 
    CGFloat      scaleFactor, width; 

    // resize, maintaining aspect ratio: 

    inputSize = self.size; 
    scaleFactor = newSize.height/inputSize.height; 
    width = roundf(inputSize.width * scaleFactor); 

    if (width > newSize.width) { 
     scaleFactor = newSize.width/inputSize.width; 
     newSize.height = roundf(inputSize.height * scaleFactor); 
    } else { 
     newSize.width = width; 
    } 

    UIGraphicsBeginImageContext(newSize); 

    context = UIGraphicsGetCurrentContext(); 

    // added 2016.07.29, flip image vertically before drawing: 
    CGContextSaveGState(context); 
    CGContextTranslateCTM(context, 0, newSize.height); 
    CGContextScaleCTM(context, 1, -1); 
    CGContextDrawImage(context, CGRectMake(0, 0, newSize.width, newSize.height, self.CGImage); 

// // alternate way to draw 
// [self drawInRect: CGRectMake(0, 0, newSize.width, newSize.height)]; 

    CGContextRestoreGState(context); 

    outputImage = UIGraphicsGetImageFromCurrentImageContext(); 

    UIGraphicsEndImageContext(); 

    inputSize = newSize; 

    // constrain crop rect to legitimate bounds 
    if (cropRect.origin.x >= inputSize.width || cropRect.origin.y >= inputSize.height) return outputImage; 
    if (cropRect.origin.x + cropRect.size.width >= inputSize.width) cropRect.size.width = inputSize.width - cropRect.origin.x; 
    if (cropRect.origin.y + cropRect.size.height >= inputSize.height) cropRect.size.height = inputSize.height - cropRect.origin.y; 

    // crop 
    if ((imageRef = CGImageCreateWithImageInRect(outputImage.CGImage, cropRect))) { 
     outputImage = [[[UIImage alloc] initWithCGImage: imageRef] autorelease]; 
     CGImageRelease(imageRef); 
    } 

    return outputImage; 
} 

@end 
+4

He probado su código y gira mi imagen 180 grados. – VansFannel

+0

¿Se ha volteado su vista? Este código funciona bien para vistas estándar. Si se voltea, es posible que tengas que alterar la matriz de transformación actual. – par

+0

Downvoters: ¿cuál es el problema? Esto funcionó bastante bien en 2010. – par

2

he encontré con el mismo problema en una de mi solicitud y desarrollado este trozo de código:

+ (UIImage*)resizeImage:(UIImage*)image toFitInSize:(CGSize)toSize 
{ 
    UIImage *result = image; 
    CGSize sourceSize = image.size; 
    CGSize targetSize = toSize; 

    BOOL needsRedraw = NO; 

    // Check if width of source image is greater than width of target image 
    // Calculate the percentage of change in width required and update it in toSize accordingly. 

    if (sourceSize.width > toSize.width) { 

     CGFloat ratioChange = (sourceSize.width - toSize.width) * 100/sourceSize.width; 

     toSize.height = sourceSize.height - (sourceSize.height * ratioChange/100); 

     needsRedraw = YES; 
    } 

    // Now we need to make sure that if we chnage the height of image in same proportion 
    // Calculate the percentage of change in width required and update it in target size variable. 
    // Also we need to again change the height of the target image in the same proportion which we 
    /// have calculated for the change. 

    if (toSize.height < targetSize.height) { 

     CGFloat ratioChange = (targetSize.height - toSize.height) * 100/targetSize.height; 

     toSize.height = targetSize.height; 
     toSize.width = toSize.width + (toSize.width * ratioChange/100); 

     needsRedraw = YES; 
    } 

    // To redraw the image 

    if (needsRedraw) { 
     UIGraphicsBeginImageContext(toSize); 
     [image drawInRect:CGRectMake(0.0, 0.0, toSize.width, toSize.height)]; 
     result = UIGraphicsGetImageFromCurrentImageContext(); 
     UIGraphicsEndImageContext(); 
    } 

    // Return the result 

    return result; 
} 

se puede modificar de acuerdo a sus necesidades.

+1

gracias por agregar esto – choise

Cuestiones relacionadas