确定UIImageView中图像的框架

时间:2019-07-07 18:30:18

标签: swift

我正在尝试确定UIImageView中图像的框架。以下是我的尝试。我用蓝色勾勒出了图像的边框。可以看出,边框似乎与图像不匹配。请有人帮忙吗?

UIImageView的自动布局是否影响了结果?

var imageView: UIImageView!
var margin: UILayoutGuide!


 let imgViewFrame = CGRect.init(x: 0, y: 0, width: margin.layoutFrame.width, height: margin.layoutFrame.height)
    let imgView = UIImageView.init(frame: imgViewFrame)
    imgView.contentMode = .scaleAspectFit
    imgView.backgroundColor = UIColor.lightGray
    view.addSubview(imgView)

    imgView.translatesAutoresizingMaskIntoConstraints = false
    imgView.topAnchor.constraint(equalTo: margin.topAnchor).isActive = true
    imgView.bottomAnchor.constraint(equalTo: margin.bottomAnchor).isActive = true
    imgView.leadingAnchor.constraint(equalTo: margin.leadingAnchor).isActive = true
    imgView.trailingAnchor.constraint(equalTo: margin.trailingAnchor).isActive = true

    let image = UIImage.init(named: imageName)
    imgView.image = image
    imageView = imgView

    //Test
    let imageRect = AVMakeRect(aspectRatio: imgView.image!.size, insideRect: self.imageView.frame)
    let imageBorderCheckView = UIView.init(frame: imageRect)
    imageBorderCheckView.layer.borderWidth = 3
    imageBorderCheckView.layer.borderColor = UIColor.blue.cgColor
    view.addSubview(imageBorderCheckView)

enter image description here

1 个答案:

答案 0 :(得分:0)

在此处使用图片框

let imageRect = AVMakeRect(aspectRatio: imgView.image!.size, insideRect: self.imageView.frame)

为时过早,请在viewDidLayoutSubviews / viewWillAppear / viewDidAppear内尝试一次

override func viewDidAppear(_ animated:Bool) {
  super.viewDidAppear(animated)
//Test
   let imageRect = AVMakeRect(aspectRatio: imgView.image!.size, insideRect: self.imageView.frame)
   let imageBorderCheckView = UIView.init(frame: imageRect)
   imageBorderCheckView.layer.borderWidth = 3
   imageBorderCheckView.layer.borderColor = UIColor.blue.cgColor
   view.addSubview(imageBorderCheckView)
}