如何在将内容模式设置为UIViewContentModeScaleAspectFit
后重新调整UIImageView的大小,以便我可以从顶部和顶部删除空格。下面。
请参阅附图
提前致谢:)
答案 0 :(得分:2)
希望这对其他人也有帮助,如果在某些条件下会破坏,请发表评论:)
- (CGRect)frameForImageattribute:(CGSize)image inImageViewAspectFit:(UIImageView *)imageView {
float imageRatio = image.width / image.height;
float viewRatio = imageView.frame.size.width / imageView.frame.size.height;
if (imageRatio < viewRatio) {
float scale = imageView.frame.size.height / image.height;
float width = scale * image.width;
return CGRectMake(kLeftPading, kTopPading, width, imageView.frame.size.height);
}
else {
float scale = imageView.frame.size.width / image.width;
float height = scale * image.height;
return CGRectMake(kLeftPading, kTopPading, imageView.frame.size.width, height);
}
}
答案 1 :(得分:0)
您需要获取图像视图的比例因子。它可以通过
获得float scaleFactor = MAX(image.size.width/imageView.bounds.size.width, image.size.height/imageView.bounds.size.height);
然后做
CGRect ivFrame = imageView.frame;
ivframe.size.height = image.size.height/scalefactor;
ivFrame.size.width = image.size.width/scalefactor;
imageView.frame = ivFrame;
theres可能是一个自动执行此操作的类别。
编辑:以下是一个用于比例因子计算,它甚至尊重mageView的内容模式:
how can I get the scale factor of a UIImageView who's mode is AspectFit?
答案 2 :(得分:0)
如果您只知道图像视图的宽度以及图像的高度是动态的,那么您需要根据给定的宽度缩放图像的高度,以删除UIViewContentModeScaleAspectFit中图像上方和下方的空白区域模式。使用here中的以下方法根据屏幕的标准宽度缩放图像的高度。
-(UIImage*)imageWithImage: (UIImage*) sourceImage scaledToWidth: (float) i_width
{
float oldWidth = sourceImage.size.width;
float scaleFactor = i_width / oldWidth;
float newHeight = sourceImage.size.height * scaleFactor;
float newWidth = oldWidth * scaleFactor;
UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight));
[sourceImage drawInRect:CGRectMake(0, 0, newWidth, newHeight)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
从你的cellForRowAtIndexPath:方法中调用它:
UIImage *img = [dictImages objectForKey:yourImageKey]; // loaded the image
cell.imgView.image = [self imageWithImage:img scaledToWidth:self.view.frame.size.width];