Na minha aplicação para iPhone, tiro uma fotografia com a câmara, depois quero redimensioná-la para 290*390 pixels. Estava a utilizar este método para redimensionar a imagem:
UIImage *newImage = [image _imageScaledToSize:CGSizeMake(290, 390)
interpolationQuality:1];
Funciona perfeitamente, mas é'é uma função não documentada, por isso posso'já não a posso utilizar com o iPhone OS4.
Então... qual é a forma mais simples de redimensionar uma imagem UII ?
A forma mais simples é definir a moldura da sua UIImageView
e definir o contentMode
para uma das opções de redimensionamento.
Ou pode usar este método de utilidade, se precisar realmente de redimensionar uma imagem:
+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
//UIGraphicsBeginImageContext(newSize);
// In next line, pass 0.0 to use the current device's pixel scaling factor (and thus account for Retina resolution).
// Pass 1.0 to force exact pixel size.
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
Exemplo de utilização:
#import "MYUtil.h"
…
UIImage *myIcon = [MYUtil imageWithImage:myUIImageInstance scaledToSize:CGSizeMake(20, 20)];
Trevor Howard tem algumas categorias UIImage que lidam com redimensionamento bastante agradável. Se nada mais puder usar o código como exemplo.
Nota: A partir de iOS 5.1, esta resposta pode ser inválida. Ver comentário abaixo.
I'também vi isto feito (que utilizo em UIButtons
para estado Normal e Selected desde que os botões don't resize
para caber). O crédito vai para quem quer que tenha sido o autor original.
Primeiro faça um ficheiro .h e .m vazio chamado UIImageResizing.h
e UIImageResizing.m
.
// Put this in UIImageResizing.h
@interface UIImage (Resize)
- (UIImage*)scaleToSize:(CGSize)size;
@end
// Put this in UIImageResizing.m
@implementation UIImage (Resize)
- (UIImage*)scaleToSize:(CGSize)size {
UIGraphicsBeginImageContext(size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(context, 0.0, size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, size.width, size.height), self.CGImage);
UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return scaledImage;
}
@end
Inclua esse ficheiro .h em qualquer ficheiro .m em que vá're usar a função e depois chame-lhe assim:
UIImage* image = [UIImage imageNamed:@"largeImage.png"];
UIImage* smallImage = [image scaleToSize:CGSizeMake(100.0f,100.0f)];