iphone - ios : set cell image dimension

标签 iphone objective-c ios xcode

我正在从我的网络服务器加载一组图像,以显示在右侧的单元格中。但是,图像的大小不同,因此显示列表时它们看起来不均匀。无论如何,我可以将图像设置为固定尺寸,例如 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;
        }
    });
});

最佳答案

您可以通过以下方法获得所需的图像尺寸。您可以将以下函数放入应用程序委托(delegate)中,并可以在整个应用程序中使用。代码如下:

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

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

祝一切顺利!!!

关于iphone - ios : set cell image dimension,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13700086/

相关文章:

iphone - 更改 UITabBarController 的 View Controller

javascript - 是否可以在 Objective-C (iphone) 中使用 JavaScript?

iOS 8 横向模式无法正常工作,应用程序不旋转

ios - 在不同的 View Controller 中执行操作

iOS JPEG 图像旋转 90 度

iphone - 如何通过示例学习 OpenGL,例如,构建一个旋转的地球仪?

ios - 如何从 iOS 8 照片框架中的 PHAsset 获取城市名称、省、州?

ios - 统一 5 和 IL2CPP : cannot build

iphone - 带有 DONE 按钮的 UIPickerView

iphone - AddressBook 框架的内存泄漏