Simple resizing image
I've been trying to use a method commonly used to resize an image. Without using this method, here is the code that takes a url of an image.
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [[UIImage alloc] initWithData:data];
cel开发者_运维知识库l.imageView.image = img;
This works fine. But when I try to use this method:
-(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize;
{
UIGraphicsBeginImageContext( newSize );
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
and call it using this:
UIImage *scaledImage = [self imageWithImage:img scaledToSize:CGSizeMake(10.0f,10.0f)];
then putting into my table like this:
cell.imageView.image = scaledImage;
Nothing shows up. Is there something I'm missing here?
This is similar to Exporting customized UITableViewCells into UIImage
Here's what you need to do in your -imageWithImage:scaledToSize: method, modified from my answer to that question:
-(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
// Create a bitmap context.
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef bitmapContextForScaledImage = CGBitmapContextCreate(nil, newSize.width, newSize.height, 8, 0, colorSpace, kCGImageAlphaNone);
CGColorSpaceRelease(colorSpace);
// Draw the image's layer into the context.
UIImageView * imageView = [[UIImageView alloc] initWithImage:image];
[imageView.layer renderInContext:bitmapContextForCell];
[imageView release];
// Create a CGImage from the context.
CGImageRef cgScaledImage = CGBitmapContextCreateImage(bitmapContextForScaledImage);
// Create a UIImage from the CGImage.
UIImage * scaledImage = [UIImage imageWithCGImage:cgScaledImage];
// Clean up.
CGImageRelease(cgScaledImage);
CGContextRelease(bitmapContextForScaledImage);
return scaledImage;
}
精彩评论