当width为设备宽度且height为原始图像的高度时,将裁剪UIImageView中的图像

时间:2019-04-03 06:23:09

标签: swift uiimageview snapkit

我创建了一个ImageViewController,用于查看长图像。 (例如漫画应用)

但是,因为UIImageView的宽度是设备宽度,所以高度是原始大小(长宽比)

但是图像被裁剪。我该怎么办?

UI代码

    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)
        }

    }

添加UIImageView代码


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
}

如何纵横比(最大宽度)UIImageView?


我找到了解决方法!

在下面的代码中添加了

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
    }

然后,设置为UIImageView。

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

1 个答案:

答案 0 :(得分:0)

由于图像的高度大于iPhone的显示高度,因此必须将图像视图置于scrollView并将内容模式设置为.scaleAspectFit并将imageView的高度设置为等于图像的高度

imgView.contentMode = .scaleAspectFit