0

我正在从我的网络服务器加载一组图像,以显示在右侧的单元格中。但是,图像有不同的大小,因此即使显示列表,它们也看起来不一样。无论如何,我可以将图像设置为固定尺寸,如 100 x 80 吗?

我的代码如下:

cell.lotImageView.image = [UIImage imageNamed:@"blankthumbnail.png"];
cell.lotImageView.clipsToBounds = YES;

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
    //load image from web server
    NSString *strURL = [NSString stringWithFormat:@"%@/images/%@", user.url, lotPhoto[row]];
    NSURL *url = [[NSURL alloc] initWithString:strURL ];
    UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];

    dispatch_async(dispatch_get_main_queue(), ^{
        // let's make sure the cell is still visible (i.e. hasn't scrolled off the screen)
        mainTableCell *cell = (mainTableCell *)[tableView cellForRowAtIndexPath:indexPath];
        if (cell)
        {
            cell.lotImageView.clipsToBounds = YES;
            cell.lotImageView.image =image;
        }
    });
});
4

2 回答 2

1

这是一种可以为图像实现所需尺寸的方法。您可以将以下功能放在您的应用程序委托中,并可以在整个应用程序中使用。这是代码:

+(UIImage *) resizeImage:(UIImage *)orginalImage resizeSize:(CGSize)size {

    CGFloat actualHeight = orginalImage.size.height;
    CGFloat actualWidth = orginalImage.size.width;
    if(actualWidth <= size.width && actualHeight<=size.height){
        return orginalImage;
        //NSLog(@"hi thassoods");
    }
    float oldRatio = actualWidth/actualHeight;
    float newRatio = size.width/size.height;
    if(oldRatio < newRatio){
        oldRatio = size.height/actualHeight;
        actualWidth = oldRatio * actualWidth;
        actualHeight = size.height;
    }
    else {
        oldRatio = size.width/actualWidth;
        actualHeight = oldRatio * actualHeight;
        actualWidth = size.width;
    }
    CGRect rect = CGRectMake(0.0,0.0,actualWidth,actualHeight);
    UIGraphicsBeginImageContext(rect.size);
    [orginalImage drawInRect:rect];
    orginalImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return orginalImage;
}

但是,是的,如果您指定的新尺寸与图像的原始尺寸不成比例,那么您的图像分辨率可能不会保持正确。

一切顺利!!!

于 2012-12-04T10:02:02.430 回答
0

您可以尝试调整图像大小。这段代码做到了:

- (UIImage *)imageWithImage:(UIImage *)image convertToSize:(CGSize)size
{
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *destImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return destImage;
}
于 2012-12-04T09:58:13.537 回答