10

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.

Greg
  • 34,042
  • 79
  • 253
  • 454
  • I finally calculate the whole things I need instead of using UIImageView with aspectFit content mode. It is convenient and is loss of many detail information. – AechoLiu Jul 18 '11 at 03:58

2 Answers2

18

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
Felix
  • 35,354
  • 13
  • 96
  • 143
  • thanks - btw re "widthScale = " line, so one should use "self.bounds.size.width" and not "self.frame.size.width" then? – Greg Jul 19 '11 at 03:16
  • 1
    @greg that makes no difference in most cases. I used bounds here because its about the size of the view itself. The bounds specify where the view may draw it's content relative to itself, the frame specifies the position relative to its superview. – Felix Jul 20 '11 at 18:03
  • should fix division by zero situation – storoj Feb 03 '16 at 12:47
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.

Mihai Fratu
  • 7,579
  • 2
  • 37
  • 63
  • thanks but I was after just the overall scale factor (noting it's an aspect fit), and I didn't want to have to detect orientation to see whether the aspect fit would have stopped first based on a width or a height (if you know what I mean) - was searching to see if there is a way to get the value without looking at frame sizes & detecting orientation.. – Greg Jul 17 '11 at 20:23