如何获得UIImageView的比例因子,其模式是AspectFit?

Gre*_*reg 8 iphone uiview uiimageview ios

如何获得UIImageView的比例因子,其模式是AspectFit?

也就是说,我有一个带有AspectFit模式的UIImageView.图像(方形)缩放到我的UIImageView框架,这很好.

如果我想获得所使用的量表(例如0.78或其他),我该如何直接得到它?

我不想比较说父视图宽度与UIImageView宽度,因为计算必须考虑方向,注意我正在将方形图像缩放为矩形视图.因此,为什么我会直接查询UIImageView以找出答案.

编辑:我需要它也适用于iPhone或iPad部署.

Fel*_*lix 16

我为此编写了一个UIImageView类别:

的UIImageView + ContentScale.h

#import <Foundation/Foundation.h>

@interface UIImageView (UIImageView_ContentScale)

-(CGFloat)contentScaleFactor;

@end
Run Code Online (Sandbox Code Playgroud)

的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
Run Code Online (Sandbox Code Playgroud)