Redimensionar e cortar imagens antes de exibir no uitableViewCells
Pergunta
Eu tenho uma View Uitable no meu aplicativo e tenho que carregar algumas imagens que têm uma largura fixa, mas alturas diferentes. Eu baixei as imagens assíncronas usando um NsoperationQueue e, para redimensionar e cortar, tentei usar a solução fornecida pelo Jane Sales neste post Texto do link.
Fiz uma classe personalizada uabableViewCell e, nela, tenho um método chamado quando a operação na fila termina para baixar a imagem. O método é chamado corretamente e as imagens são exibidas. Quando tento redimensionar as imagens usando o método proposto por Jane, os problemas aparecem. Quando chega ORONTIMAGE DREATINRECT: ThumbnailRect]; Recebo um erro de acesso ruim do EXEC e não consigo descobrir o porquê. Eu chamo o método como este:
- (void) setupImage:(UIImage *) anImage{
UIImage *resized = [anImage imageByScalingAndCroppingForSize:CGSizeMake(64, 59)];
if(resized == nil)
resized = [UIImage newImageFromResource:@"thumb2.png"];
[thumbnailView setImage:resized];
}
Configuração é a função chamada quando o NSoperCeUe termina a ação de download de uma imagem.
Alguém poderia me dar uma pista por que recebo o erro de acesso ruim do EXEC quando tento redimensionar e cortar as imagens? Tentei usar a mesma função fora da visualização da tabela. 80% dos casos em que funciona, mas há casos em que recebo o mesmo erro de acesso ruim do executivo.
Agradeço antecipadamente, Sorin
Solução
É isso que estou usando para redimensionar e cultivar os uiimages (o código é de Solução de vendas de Jane)
@implementation UIImage (Extras)
#pragma mark -
#pragma mark Scale and crop image
- (UIImage*)imageByScalingAndCroppingForSize:(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; // scale to fit height
else
scaleFactor = heightFactor; // scale to fit width
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;
}
}
UIGraphicsBeginImageContext(targetSize); // this will crop
CGRect thumbnailRect = CGRectZero;
thumbnailRect.origin = thumbnailPoint;
thumbnailRect.size.width = scaledWidth;
thumbnailRect.size.height = scaledHeight;
[sourceImage drawInRect:thumbnailRect];
newImage = UIGraphicsGetImageFromCurrentImageContext();
if(newImage == nil)
NSLog(@"could not scale image");
//pop the context to get back to the default
UIGraphicsEndImageContext();
return newImage;
}
Eu chamo a função acima como eu disse antes:
- (void) setupImage:(UIImage *) anImage
{
UIImage *resized = [anImage imageByScalingAndCroppingForSize:CGSizeMake(64, 59)];
[thumbnailView setImage:resized];
}
As imagens são baixadas assync quando uma célula é exibida na visualização da tabela. A função Setupimage recebe a imagem de uma NSoperation que o baixa assíncrona. O problema é que, como eu disse acima, quando atinge [o SOURCEIMAGE DrawinRect: ThumbnailRect];
O ThumbnailView é um UIImageView que é uma subjusta do meu TableViewCell personalizado.
Espero que isso esclareça um pouco as coisas sobre o que estou usando no meu código. Obrigado pela ajuda. Sorin
Outras dicas
Experimente o seguinte código. O método CreateImage: Image: Largura: Altura requer uma fonte CGIMAGEREF e a nova largura e altura da UIImage final que será retornada. Ao usar como fonte de UIImage, você pode obter o CGIMAGEREF correspondente da seguinte maneira:
UIImage *sourceImage;
CGImageRef *sourceRef = [sourceImage CGImage];
// Draw the image into a pixelsWide x pixelsHigh bitmap and use that bitmap to
// create a new UIImage
- (UIImage *) createImage: (CGImageRef) image width: (int) pixelWidth height: (int) pixelHeight
{
// Set the size of the output image
CGRect aRect = CGRectMake(0.0f, 0.0f, pixelWidth, pixelHeight);
// Create a bitmap context to store the new thumbnail
CGContextRef context = MyCreateBitmapContext(pixelWidth, pixelHeight);
// Clear the context and draw the image into the rectangle
CGContextClearRect(context, aRect);
CGContextDrawImage(context, aRect, image);
// Return a UIImage populated with the new resized image
CGImageRef myRef = CGBitmapContextCreateImage (context);
UIImage *img = [UIImage imageWithCGImage:myRef];
free(CGBitmapContextGetData(context));
CGContextRelease(context);
CGImageRelease(myRef);
return img;
}
// MyCreateBitmapContext: Source based on Apple Sample Code
CGContextRef MyCreateBitmapContext (int pixelsWide,
int pixelsHigh)
{
CGContextRef context = NULL;
CGColorSpaceRef colorSpace;
void * bitmapData;
int bitmapByteCount;
int bitmapBytesPerRow;
bitmapBytesPerRow = (pixelsWide * 4);
bitmapByteCount = (bitmapBytesPerRow * pixelsHigh);
colorSpace = CGColorSpaceCreateDeviceRGB();
bitmapData = malloc( bitmapByteCount );
if (bitmapData == NULL)
{
fprintf (stderr, "Memory not allocated!");
CGColorSpaceRelease( colorSpace );
return NULL;
}
context = CGBitmapContextCreate (bitmapData,
pixelsWide,
pixelsHigh,
8,
bitmapBytesPerRow,
colorSpace,
kCGImageAlphaPremultipliedLast);
if (context== NULL)
{
free (bitmapData);
CGColorSpaceRelease( colorSpace );
fprintf (stderr, "Context not created!");
return NULL;
}
CGColorSpaceRelease( colorSpace );
return context;
}