I am loading an image to an imageview with mode as 'Aspect Fit'. I need to know the size to which my image is being scaled to. Please help.
Why not use the OS function AVMakeRectWithAspectRatioInsideRect?
I wanted to use AVMakeRectWithAspectRatioInsideRect()
without including the AVFoundation framework.
So I've implemented the following two utility functions:
CGSize CGSizeAspectFit(CGSize aspectRatio, CGSize boundingSize) { float mW = boundingSize.width / aspectRatio.width; float mH = boundingSize.height / aspectRatio.height; if( mH < mW ) boundingSize.width = boundingSize.height / aspectRatio.height * aspectRatio.width; else if( mW < mH ) boundingSize.height = boundingSize.width / aspectRatio.width * aspectRatio.height; return boundingSize; } CGSize CGSizeAspectFill(CGSize aspectRatio, CGSize minimumSize) { float mW = minimumSize.width / aspectRatio.width; float mH = minimumSize.height / aspectRatio.height; if( mH > mW ) minimumSize.width = minimumSize.height / aspectRatio.height * aspectRatio.width; else if( mW > mH ) minimumSize.height = minimumSize.width / aspectRatio.width * aspectRatio.height; return minimumSize; }
Edit: Optimized below by removing duplicate divisions.
CGSize CGSizeAspectFit(const CGSize aspectRatio, const CGSize boundingSize) { CGSize aspectFitSize = CGSizeMake(boundingSize.width, boundingSize.height); float mW = boundingSize.width / aspectRatio.width; float mH = boundingSize.height / aspectRatio.height; if( mH < mW ) aspectFitSize.width = mH * aspectRatio.width; else if( mW < mH ) aspectFitSize.height = mW * aspectRatio.height; return aspectFitSize; } CGSize CGSizeAspectFill(const CGSize aspectRatio, const CGSize minimumSize) { CGSize aspectFillSize = CGSizeMake(minimumSize.width, minimumSize.height); float mW = minimumSize.width / aspectRatio.width; float mH = minimumSize.height / aspectRatio.height; if( mH > mW ) aspectFillSize.width = mH * aspectRatio.width; else if( mW > mH ) aspectFillSize.height = mW * aspectRatio.height; return aspectFillSize; }
End of edit
This takes a given size (first parameter) and maintains its aspect ratio. It then fills the given bounds (second parameter) as much as possible without violating the aspect ratio.
Using this to answer the original question:
// Using aspect fit, scale the image (size) to the image view's size. CGSize sizeBeingScaledTo = CGSizeAspectFit(theImage.size, theImageView.frame.size);
Note how the image determines the aspect ratio, while the image view determines the size to be filled.
Feedback is very welcome.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With