调整 UIImageView 的大小以适合屏幕



有一个UIImageView作为属性通过另一个视图控制器的segue传递,用户在图像上潦草地写了一遍。我无法调整/缩放图像以适应接收视图控制器中的UIView。无论我尝试什么,它都会越过屏幕。

以下是我在viewDidLoad()中尝试过的一些零成功

incomingImgView?.frame = CGRect(x: 0, y: 0, width: view.bounds.width  , height:  view.bounds.height)
// incomingImgView?.frame = CGRect(x: 0, y: 0, width: 100  , height: 100)
incomingImgView?.contentMode = .scaleAspectFit
incomingImgView?.clipsToBounds = true
//incomingImgView?.frame = view.bounds
viewContainer.addSubview(incomingImgView!)

// incomingImgView?.image?.scaleImage(toSize: CGSize(width: 100, height: 100))
// incomingImgView?.layoutIfNeeded()
view.layoutIfNeeded()

请尝试以下操作:

 incomingImgView?.frame = CGRect(x: 0, y: 0, width: viewContainer.bounds.width  , height:  viewContainer.bounds.height)

您设置帧两次,因此第一次尝试设置时将替换为帧incomingImgView?.frame = view.bounds,因此它将采用view.bounds帧而不是incomingImgView?.frame = CGRect(x: 0, y: 0, width: view.bounds.width , height: view.bounds.height)帧。

尝试以下代码并检查

   incomingImgView?.frame = CGRect(x: 0, y: 0, width: 100  , height: 100)
   incomingImgView?.contentMode = .scaleAspectFit    
   incomingImgView?.clipsToBounds = true
   viewContainer.addSubview(incomingImgView!)    

我已经处理这个确切的问题一段时间了,并为我创建的从 UIImageView 继承的类提出了这个解决方案(请注意,如果这是您唯一要更改的内容,您可能可以将其作为 UIImageView 本身的扩展,而不是创建一个新类):

func scaleAndCenterInParent(){
    //Scales and centers to superview
    if let screenSize = superview?.frame.size{
        let frameSize = self.frame.size

        if frameSize.width > screenSize.width || frameSize.height > screenSize.height{
            //Image exceeds screen in at least one direction
            var scale: CGFloat = 1
            let frameRatio = (frameSize.width)/(frameSize.height)
            if frameRatio >= 1{
                //landscape frame
                scale = screenSize.width/frameSize.width
            }else{
                //portrait frame
                scale = screenSize.height/frameSize.height
            }
            //apply transform to self (imageview)
            self.transform = self.transform.scaledBy(x: scale, y: scale)

            //center
            self.frame.origin.x = (superview!.bounds.midX - (frameSize.width*0.5))
            self.frame.origin.y = (superview!.bounds.midY - (frameSize.height*0.5))
        }
    }
}

编辑:请注意,您仍然需要设置.scaleAspectFit参数,因为这只会更改框架的大小。它保留了完整的图像质量。

你有没有试过incomingImgView.sizeToFit() 此方法使视图适合其父视图的正确大小。

最新更新