how can I get the scale factor of a UIImageView who's mode is AspectFit?

随声附和 提交于 2020-01-09 19:13:37

问题


how can I get the scale factor of a UIImageView who's mode is AspectFit?

That is, I have a UIImageView with mode AspectFit. The image (square) is scaled to my UIImageView frame which is fine.

If I want to get the amount of scale that was used (e.g. 0.78 or whatever) how can I get this directly?

I don't want to have to compare say a parent view width to the UIImageView width as the calculation would have to take into account orientation, noting I'm scaling a square image into a rectangular view. Hence why I was after a direct way to query the UIImageView to find out.

EDIT: I need it to work for iPhone or iPad deployment as well.


回答1:


I've written a UIImageView category for that:

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



回答2:


Well you could do something like

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

Let me know if that works for you.



来源:https://stackoverflow.com/questions/6726423/how-can-i-get-the-scale-factor-of-a-uiimageview-whos-mode-is-aspectfit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!