所以在我的TableViewCell中,我有一个标签,在标签下面,我有一个尺寸为(320 * 320)的imageview,在imageview下面我还有另外一些UIView。我的tableview使用自动行高,我从URL下载图像并加载到imageview。我也使用sdwebimage缓存来下载图像后缓存图像。
我现在的问题是横向图像(图像宽度<图像高度),我使用AspectFit很好,图像很适合在imageview中。然而,对于肖像图像(图像宽度>图像高度),图像将不会填充图像视图的整个高度(因为我使用的是aspectfit)并且它将在顶部和底部标签与UIView之间留下空白。
我尝试调整imageview高度以将其缩小到图像的高度。我所做的是在下载图像方法的完成块中,我检查图像宽度是否更大,然后我将图像视图更改为具有新的调整大小高度的新图像视图,但我无法使其与autolayout一起使用。当图像首先显示时,它的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];
}
}];