Search code examples
swiftuiimageviewcore-graphics

Get Size of UImage when in UIImageView when ContentMode = AspectFill


Im currently editing an UIImage with core graphics

The UIImage content mode is set to .aspectFill

When I draw on the image I want to keep the scale / ratio of the image.

Ive tried the following code but it returns .aspectFit values rather then .AspectFill

let imageSize = AVMakeRect(aspectRatio: (mainImageView.image?.size)!, insideRect: mainImageView.frame)

Any help would be greatly appreciated

Thomas


Solution

  • That function can only do an aspect fit.

    Here is a function that will do an aspect fill:

    func makeFillRect(aspectRatio: CGSize, insideRect: CGRect) -> CGRect {
        let aspectRatioFraction = aspectRatio.width / aspectRatio.height
        let insideRectFraction = insideRect.size.width / insideRect.size.height
        let r: CGRect
        if (aspectRatioFraction > insideRectFraction) {
            let w = insideRect.size.height * aspectRatioFraction
            r = CGRect(x: (insideRect.size.width - w)/2, y: 0, width: w, height: insideRect.size.height)
        } else {
            let h = insideRect.size.width / aspectRatioFraction
            r = CGRect(x: 0, y: (insideRect.size.height - h)/2, width: insideRect.size.width, height: h)
        }
        return r
    }