1

所以在我的 TableViewCell 中,我有一个标签,在标签下方,我有一个大小为 (320*320) 的图像视图,在图像视图下方我有另一个 UIView,里面有一些东西。我的 tableview 正在使用自动行高,我正在从 URL 下载图像并加载到 imageview 上。下载图像后,我还使用 sdwebimage 缓存来缓存图像。

我现在的问题是横向图像(图像宽度<图像高度),我可以很好地使用 AspectFit 并且图像很好地适合图像视图。但是,对于纵向图像(图像宽度 > 图像高度),图像不会填满图像视图的整个高度(因为我使用的是 aspectfit),并且它会在顶部和底部标签与 UIView 之间留下空白。

我试图调整图像视图的高度以将其缩小到图像的高度。我所做的是在下载图像方法的完成块中,我检查图像宽度是否较大,然后将图像视图更改为具有新调整大小的高度的新图像视图,但我无法使其与自动布局一起使用。当图像首先显示时,它的 imageview 似乎已经调整大小,但是当我向下滚动并滚动备份时,它不再工作。

下面是我在 cellForRowAtIndexPath 方法中使用的代码。

[[SDImageCache sharedImageCache] queryDiskCacheForKey:cacheKey done:^(UIImage *image, SDImageCacheType cacheType) {
    if (image != nil) {
        float maxWidth = self.productImageView.frame.size.width;
        float maxHeight = self.productImageView.frame.size.height;
        float actualWidth = image.size.width;
        float actualHeight = image.size.height;
        float imageRatio = actualWidth/actualHeight;

        if (actualWidth > actualHeight) {
            imageRatio = maxWidth/actualWidth;
            actualHeight = imageRatio * actualHeight;

            if (actualHeight < maxHeight) {
                self.productImageView.frame = CGRectMake(self.productImageView.frame.origin.x, self.productImageView.frame.origin.y, maxWidth, actualHeight);
            }
        }

        self.productImageView.contentMode = UIViewContentModeScaleAspectFit;
        self.productImageView.image = image;
        self.productImageView.clipsToBounds = YES;
    } else {
        // download image from remote server
        [self downloadProductImage:sellPost.productImageURL withCacheKey:cacheKey];
    }
}];
4

0 回答 0