Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 827
Greg Avatar asked Jul 17 '11 20:07

Greg


People also ask

How do I change aspect ratio in UIImageView?

If you are resizing UIImageView manually, set the content mode to UIViewContentModeScaleAspectFill . If you want to keep content mode UIViewContentModeScaleAspectFit do not resize imageview to 313. Image will adjust maximum possible width and height , keeping it's aspect ratio.

What is Uiimage?

An object that manages image data in your app.

What is imageView in Swift?

A view that displays a single image or a sequence of animated images in your interface.

How do I fit an image in Swift?

Swift. You can use the following options to position your image: scaleToFill. scaleAspectFit // contents scaled to fit with fixed aspect.


1 Answers

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
like image 195
Felix Avatar answered Oct 16 '22 16:10

Felix