我有UIImageView
内容模式 Aspect Fit ,大小为220x155。我正在以不同的分辨率动态插入不同的图像,但都大于UIImageView的大小。当内容模式设置为 Aspect Fit 时,图像将根据比率进行缩放以适合UIImageView。
我的问题是,如果例如UIImageView中的图像缩放到220x100,我希望UIImageView也从155到100的高度缩小,以避免我的元素之间的空间。
我该怎么做?
答案 0 :(得分:28)
如果我找对你,那就是这样的:通过以下方式获取图像尺寸:
UIImage * img = [UIImage imageNamed:@"someImage.png"];
CGSize imgSize = img.size;
计算宽度上的比例
float ratio=yourImageView.frame.size.width/imgSize.width;
检查缩放高度(使用相同的比例保持方位)
float scaledHeight=imgSize.height*ratio;
if(scaledHeight < yourImageView.frame.size.height)
{
//update height of your imageView frame with scaledHeight
}
答案 1 :(得分:20)
根据Michael的回答,这是一个完整的方法
+ (CGSize)makeSize:(CGSize)originalSize fitInSize:(CGSize)boxSize
{
float widthScale = 0;
float heightScale = 0;
widthScale = boxSize.width/originalSize.width;
heightScale = boxSize.height/originalSize.height;
float scale = MIN(widthScale, heightScale);
CGSize newSize = CGSizeMake(originalSize.width * scale, originalSize.height * scale);
return newSize;
}
答案 2 :(得分:3)
编辑Steven Stefanik的答案:当originalSize为{0,0}时,此方法会中断。也许考虑一下这些变化
-(CGSize)makeSize:(CGSize)originalSize fitInSize:(CGSize)boxSize
{
if (originalSize.height == 0) {
originalSize.height = boxSize.height;
}
if (originalSize.width == 0) {
originalSize.width = boxSize.width;
}
float widthScale = 0;
float heightScale = 0;
widthScale = boxSize.width/originalSize.width;
heightScale = boxSize.height/originalSize.height;
float scale = MIN(widthScale, heightScale);
CGSize newSize = CGSizeMake(originalSize.width * scale, originalSize.height * scale);
return newSize;
}
答案 3 :(得分:0)
上次修改:
我似乎误解了这个问题。
要获得实际尺寸,您可以尝试:
CGSize imageSize = img.size;
CGSize viewSize = imageView.frame.size;
CGSize actualSize;
if (imageSize.width > imageSize.height) {
actualSize.width = imageSize.width > viewSize.width ? viewSize.width : imageSize.width;
actualSize.height = imageSize.height * actualSize.width / imageSize.width;
}
else {
actualSize.height = imageSize.height > viewSize.height ? viewSize.height : imageSize.height;
actualSize.width = imageSize.width * actualSize.height / imageSize.height;
}