如何获取UIImageView的缩放比例,其模式为AspectFit?

10

如何获取UIImageView以AspectFit模式缩放的比例因子?

也就是说,我有一个使用AspectFit模式的UIImageView。图像(正方形)被缩放到我的UIImageView框架中,这很好。

如果我想直接获取已使用的缩放比例(例如0.78或其他),我该怎么做?

我不想将父视图宽度与UIImageView宽度进行比较,因为计算必须考虑方向,要注意我正在将正方形图像缩放到矩形视图中。因此,我需要一种直接查询UIImageView以查找的方法。

编辑:我需要它在iPhone或iPad上部署时也能正常工作。


我终于计算出了我需要的所有东西,而不是使用UIImageView和aspectFit内容模式。这样做很方便,但会丢失许多详细信息。 - AechoLiu
2个回答

18
我已经为此编写了一个UIImageView类别:
UIImageView+ContentScale.h
#import <Foundation/Foundation.h>

@interface UIImageView (UIImageView_ContentScale)

-(CGFloat)contentScaleFactor;

@end

UIImageView+ContentScale.m

#import "UIImageView+ContentScale.h"

@implementation UIImageView (UIImageView_ContentScale)

-(CGFloat)contentScaleFactor
{
    CGFloat widthScale = self.bounds.size.width / self.image.size.width;
    CGFloat heightScale = self.bounds.size.height / self.image.size.height;

    if (self.contentMode == UIViewContentModeScaleToFill) {
        return (widthScale==heightScale) ? widthScale : NAN;
    }
    if (self.contentMode == UIViewContentModeScaleAspectFit) {
        return MIN(widthScale, heightScale);
    }
    if (self.contentMode == UIViewContentModeScaleAspectFill) {
        return MAX(widthScale, heightScale);
    }
    return 1.0;

}

@end

谢谢。顺便提一下,“widthScale =”这一行,应该使用“self.bounds.size.width”,而不是“self.frame.size.width”,对吗? - Greg
1
@greg,在大多数情况下这没有什么区别。我在这里使用bounds是因为它与视图本身的大小有关。bounds指定了视图相对于自身绘制其内容的位置,而frame则指定了相对于其父视图的位置。 - Felix
应该修复除以零的情况。 - storoj

2

你可以这样操作

CGFloat widthScale = imageView.image.size.width / imageView.frame.size.width;
CGFloat heightScale = imageView.image.size.height / imageView.frame.size.height;

如果这个对你有用,请告诉我。

谢谢,但我只是想要总体比例因子(注意这是一个纵横比适合),而且我不想检测方向来确定纵横比是否基于宽度或高度先停止(如果你知道我的意思) - 正在搜索是否有一种方法可以在不查看帧大小和检测方向的情况下获取该值。 - Greg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接