0
votes

I created an ImageViewController, that is used to view long images. (like comics app)

but, as it is UIImageView's width is device-width, height is original size(aspect ratio)

But the image is cropped. How do I do it?

UI Code

    fileprivate let scrollView = UIScrollView().then {
        $0.translatesAutoresizingMaskIntoConstraints = false
        $0.backgroundColor = .yellow
        $0.bounces = false
    }

    fileprivate let stackView = UIStackView().then {
        $0.translatesAutoresizingMaskIntoConstraints = false
        $0.axis = .vertical
    }

    // MARK: - View Life Cycle
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.addSubview(self.scrollView)
        self.scrollView.addSubview(self.stackView)

        self.scrollView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        self.stackView.snp.makeConstraints { make in
            make.edges.equalTo(self.scrollView)
        }

    }

Add UIImageView code


for element in lists {
    let imgView = UIImageView()
    imgView.setImage(element) // set image from url

    imgView.contentMode = .scaleAspectFill

    imgView.clipsToBounds = true
    imgView.translatesAutoresizingMaskIntoConstraints = false
    self.stackView.addArrangedSubview(imgView)
    imgView.widthAnchor.constraint(equalTo:    self.scrollView.widthAnchor, multiplier: 1.0).isActive = true
    imgView.heightAnchor.constraint(equalTo:     self.scrollView.heightAnchor, multiplier: 1.0).isActive = true
}

How to aspect ratio(max width) UIImageView?


I found solution!

added below code,

func imageScaled(with sourceImage: UIImage?, scaledToWidth i_width: Float) -> UIImage? {
        let oldWidth = Float(sourceImage?.size.width ?? 0.0)
        let scaleFactor: Float = i_width / oldWidth

        let newHeight = Float((sourceImage?.size.height ?? 0.0) * CGFloat(scaleFactor))
        let newWidth: Float = oldWidth * scaleFactor
        print(newHeight)

        UIGraphicsBeginImageContext(CGSize(width: CGFloat(newWidth), height: CGFloat(newHeight)))
        sourceImage?.draw(in: CGRect(x: 0, y: 0, width: CGFloat(newWidth), height: CGFloat(newHeight)))
        let newImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage
    }

then, set to UIImageView.

imgView.setImageScaled(element, width: Float(self.scrollView.frame.width))
1

1 Answers

0
votes

as your image is bigger in height then the iphone's display height you have to put your image view in the scrollView and set content mode to .scaleAspectFit and set imageView's height equal to image's height

imgView.contentMode = .scaleAspectFit