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.
相关问题
- CALayer - backgroundColor flipped?
- Core Data lightweight migration crashes after App
- How can I implement password recovery in an iPhone
- SwiftUI: UIImage (QRCode) does not load after call
- how do you prevent page scroll in textarea on mobi
相关文章
- Could I create “Call” button in HTML 5 IPhone appl
- Unable to process app at this time due to a genera
- How do you detect key up / key down events from a
- “Storyboard.storyboard” could not be opened
- Custom Marker performance iOS, crash with result “
- Open iOS 11 Files app via URL Scheme or some other
- Can keyboard of type UIKeyboardTypeNamePhonePad be
- Can not export audiofiles via “open in:” from Voic
I wanted to use
AVMakeRectWithAspectRatioInsideRect()
without including the AVFoundation framework.So I've implemented the following two utility functions:
Edit: Optimized below by removing duplicate divisions.
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:
Note how the image determines the aspect ratio, while the image view determines the size to be filled.
Feedback is very welcome.
Swift 4: Frame for
.aspectFit
image is -let x: CGRect = AVMakeRect(aspectRatio: myImage.size, insideRect: sampleImageView.frame)
Maybe does not fit your case, but this simple approach solve my problem in a similar case:
After image view executes sizeToFit if you query the imageView.frame.size you will get the new image view size that fits the new image size.
Swift 4 version
The accepted answer is incredibly complicated and fails for some edge cases. I think this solution is much more elegant:
The above mentioned methods never give the required values.As aspect fit maintains the same aspect ratio we just need simple maths to calculate the values
Detect the aspect ratio
Get the new values