0

I am trying to change the NSLayout constraint constant by getting the imageview content position as CGRECT. But the content position i am getting by using contentRect is different.

Here is the extension i am using to get the content position.

extension UIImageView {

      var contentRect: CGRect {
        guard let image = image else { return bounds }
        guard contentMode == .scaleAspectFit else { return bounds }
        guard image.size.width > 0 && image.size.height > 0 else { return bounds }

        let scale: CGFloat
        if image.size.width > image.size.height {
            scale = bounds.width / image.size.width
        } else {
            scale = bounds.height / image.size.height
        }

        let size = CGSize(width: image.size.width * scale, height: image.size.height * scale)
        let x = (bounds.width - size.width) / 2.0
        let y = (bounds.height - size.height) / 2.0

        return CGRect(x: x, y: y, width: size.width, height: size.height)
    }

 override func viewDidLoad(){

        super.viewDidLoad()

        imageVw.image = imagePassed
        imageVw.backgroundColor = colorPassed
        setStyle(toTextField: topText)
        setStyle(toTextField: bottomText)
        let ht = imageVw.contentRect.minY + imageVw.contentSize.height
        topConstraint.constant = self.view.frame.height - ht
        self.view.layoutIfNeeded()

        print("contentRect value  \(imageVw.contentRect)")
        print("point   \(imageVw.contentRect.minY)")
        print("image height  \(imageVw.contentSize)")

    }
manishsharma93
  • 1,039
  • 1
  • 11
  • 26
Sanj12
  • 1
  • 4
  • Possible duplicate of [How to resize UIImageView based on UIImage's size/ratio in Swift 3?](https://stackoverflow.com/questions/41154784/how-to-resize-uiimageview-based-on-uiimages-size-ratio-in-swift-3) – えるまる Sep 03 '19 at 05:24
  • No that link is irrelavant – Sanj12 Sep 03 '19 at 05:46
  • I don't really get, what you are trying to achieve. A constant of a NSLayoutConstraint is "constant", so you usually use it, because you know what value it should be. If that "constant" should be "flexible" following the individual imageSize, then this is the wrong approach, search for "intrinsicSize" instead, maybe this helps. – LukeSideWalker Sep 03 '19 at 10:44
  • @LukeSideWalker Yes, you are right. All i needed to do is change the aspect ratio. Thanks for your hel – Sanj12 Sep 04 '19 at 06:43

0 Answers0