UIImage size in UIImageView

前端 未结 4 518
天涯浪人
天涯浪人 2021-01-06 18:40

I have some UIImage and display it in UIImageView.

I need to use UIViewContentModeScaleAspectFit content mode.

Here i

4条回答
  •  鱼传尺愫
    2021-01-06 18:46

    In swift, same as @jacob-relkin

    extension UIImageView {
    
        func displayedImageBounds() -> CGRect {
    
            let boundsWidth = bounds.size.width
            let boundsHeight = bounds.size.height
            let imageSize = image!.size
            let imageRatio = imageSize.width / imageSize.height
            let viewRatio = boundsWidth / boundsHeight
            if ( viewRatio > imageRatio ) {
                let scale = boundsHeight / imageSize.height
                let width = scale * imageSize.width
                let topLeftX = (boundsWidth - width) * 0.5
                return CGRectMake(topLeftX, 0, width, boundsHeight)
            }
            let scale = boundsWidth / imageSize.width
            let height = scale * imageSize.height
            let topLeftY = (boundsHeight - height) * 0.5
            return CGRectMake(0,topLeftY, boundsWidth,height)
        }
    }
    

提交回复
热议问题