简单调整图像大小

时间:2010-11-16 22:10:24

标签: iphone resize-image

我一直在尝试使用常用于调整图像大小的方法。不使用此方法,这里是获取图像网址的代码。

NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [[UIImage alloc] initWithData:data];

cell.imageView.image = img;

这很好用。但是当我尝试使用这种方法时:

-(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize;
{
    UIGraphicsBeginImageContext( newSize );
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

并使用它来调用它:

UIImage *scaledImage = [self imageWithImage:img scaledToSize:CGSizeMake(10.0f,10.0f)];

然后像这样放入我的桌子:

cell.imageView.image = scaledImage;

什么都没有出现。这里有什么我想念的吗?

1 个答案:

答案 0 :(得分:1)

这类似于Exporting customized UITableViewCells into UIImage

这是你需要在-imageWithImage:scaledToSize:方法中做的,根据我对该问题的回答进行修改:

-(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;
}