调整UIImageView的大小以适应屏幕

时间:2017-01-11 11:44:39

标签: ios swift

有一个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()

4 个答案:

答案 0 :(得分:1)

请试试这个:

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

答案 1 :(得分:0)

您正在设置两次框架,因此第一次尝试设置时会替换为框架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!)    

答案 2 :(得分:0)

我一直在处理这个确切的问题一段时间,并为我继承自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参数,因为这只会更改框架的大小。它保留了完整的图像质量。

答案 3 :(得分:0)

您是否尝试过incomingImgView.sizeToFit()此方法使视图适合其父视图的正确大小。

相关问题