¿Cómo escalar un UIImageView proporcionalmente?

Resuelto Ronnie Liew asked hace 15 años • 0 respuestas

Tengo un UIImageView y el objetivo es reducirlo proporcionalmente dándole altura o ancho.

UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://farm4.static.flickr.com/3092/2915896504_a88b69c9de.jpg"]]];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; 

//Add image view
[self.view addSubview:imageView];   

//set contentMode to scale aspect to fit
imageView.contentMode = UIViewContentModeScaleAspectFit;

//change width of frame
CGRect frame = imageView.frame;
frame.size.width = 100;
imageView.frame = frame;

Se cambió el tamaño de la imagen, pero la posición no está en la parte superior izquierda. ¿Cuál es el mejor enfoque para escalar una imagen/imageView y cómo corrijo la posición?

Ronnie Liew avatar Oct 09 '08 08:10 Ronnie Liew
Aceptado

¡Se solucionó fácilmente una vez que encontré la documentación!

 imageView.contentMode = .scaleAspectFit
Ken Abrams avatar Feb 20 '2010 00:02 Ken Abrams

He visto un poco de conversación sobre los tipos de escala, así que decidí elaborar un artículo sobre algunos de los tipos de escala de modo de contenido más populares .

La imagen asociada está aquí:

ingrese la descripción de la imagen aquí

Jacksonkr avatar Jan 08 '2013 17:01 Jacksonkr

Acabo de intentar esto y UIImage no es compatible con _imageScaledToSize.

Terminé agregando un método a UIImage usando una categoría, una sugerencia que encontré en los foros de desarrolladores de Apple.

En un .h de todo el proyecto -

@interface UIImage (Extras)
- (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize;
@end;

Implementación:

@implementation UIImage (Extras)

- (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize {

    UIImage *sourceImage = self;
    UIImage *newImage = nil;

    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;

    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;

    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;

    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);

    if (CGSizeEqualToSize(imageSize, targetSize) == NO) {

        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;

        if (widthFactor < heightFactor) 
            scaleFactor = widthFactor;
        else
            scaleFactor = heightFactor;

        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;

        // center the image

        if (widthFactor < heightFactor) {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5; 
        } else if (widthFactor > heightFactor) {
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }


    // this is actually the interesting part:

    UIGraphicsBeginImageContext(targetSize);

    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;

    [sourceImage drawInRect:thumbnailRect];

    newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    if(newImage == nil) NSLog(@"could not scale image");


    return newImage ;
}

@end;
Jane Sales avatar Feb 11 '2009 16:02 Jane Sales
imageView.contentMode = UIViewContentModeScaleAspectFill;
imageView.clipsToBounds = YES;
Li-chih Wu avatar Dec 11 '2012 07:12 Li-chih Wu

Podrías intentar hacer que el imageViewtamaño coincida con el image. El siguiente código no se prueba.

CGSize kMaxImageViewSize = {.width = 100, .height = 100};
CGSize imageSize = image.size;
CGFloat aspectRatio = imageSize.width / imageSize.height;
CGRect frame = imageView.frame;
if (kMaxImageViewSize.width / aspectRatio <= kMaxImageViewSize.height) 
{
    frame.size.width = kMaxImageViewSize.width;
    frame.size.height = frame.size.width / aspectRatio;
} 
else 
{
    frame.size.height = kMaxImageViewSize.height;
    frame.size.width = frame.size.height * aspectRatio;
}
imageView.frame = frame;
Chris Lundie avatar Oct 09 '2008 04:10 Chris Lundie