swift 如何使背景图片适合在滚动视图?

jv4diomz  于 2023-05-05  发布在  Swift
关注(0)|答案(1)|浏览(165)

scaleAspectfit似乎不起作用。我试着让我的整个背景图像稍微融入背景,看到更多的图像。我添加了一个滚动视图,这样用户就可以上下滚动一点来查看图像。
但是,我的应用程序太放大图像了。

lazy var scrollView: UIScrollView = {
    let view = UIScrollView()
    view.translatesAutoresizingMaskIntoConstraints = false
    view.contentSize.height = 800
    view.bounces = true
    return view
}()

override func viewDidLoad(){ super.viewDidLoad()

let backgroundImage = UIImageView(frame: UIScreen.main.bounds)
    backgroundImage.image = UIImage(named: "backgroundImage.png")
    backgroundImage.contentMode = UIViewContentMode.scaleAspectFit
    view.insertSubview(backgroundImage, at: 0)

    view.addSubview(scrollView)
    scrollView.anchor(top: view.topAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 0)

    scrollView.addSubview(backgroundImage)
    backgroundImage.center(x: scrollView.centerXAnchor, y: scrollView.centerYAnchor)

 }

//如果你们想知道的话,这只是我用于自动布局的扩展

extension UIView {

func anchor(top: NSLayoutYAxisAnchor?, left: NSLayoutXAxisAnchor?, bottom: NSLayoutYAxisAnchor?, right: NSLayoutXAxisAnchor?, paddingTop: CGFloat, paddingLeft: CGFloat, paddingBottom: CGFloat, paddingRight: CGFloat, width: CGFloat, height: CGFloat) {

    translatesAutoresizingMaskIntoConstraints = false

    if let top = top {
        topAnchor.constraint(equalTo: top, constant: paddingTop).isActive = true
    }

    if let left = left {
        leftAnchor.constraint(equalTo: left, constant: paddingLeft).isActive = true
    }

    if let bottom = bottom {
        bottomAnchor.constraint(equalTo: bottom, constant: -paddingBottom).isActive = true
    }

    if let right = right {
        rightAnchor.constraint(equalTo: right, constant: -paddingRight).isActive = true
    }

    if width != 0 {
        widthAnchor.constraint(equalToConstant: width).isActive = true
    }

    if height != 0 {
        heightAnchor.constraint(equalToConstant: height).isActive = true
    }

func center(x: NSLayoutXAxisAnchor?, y: NSLayoutYAxisAnchor? ) {

    translatesAutoresizingMaskIntoConstraints = false

    if let x = x {
        centerXAnchor.constraint(equalTo: x).isActive = true
    }

    if let y = y {
        centerYAnchor.constraint(equalTo: y).isActive = true
    }
}
}
pu82cl6c

pu82cl6c1#

首先在此处添加两处相同的imageView

view.insertSubview(backgroundImage, at: 0)

还有这里

scrollView.addSubview(backgroundImage)

所以最终它将只被添加到scrollView中,因为它是一个对象

其次需要这样约束imageView

backgroundImage.anchor(top: scrollView.topAnchor, left: scrollView.leftAnchor, bottom: scrollView.bottomAnchor, right: scrollView.rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 0)

然后根据scrollView内容拉伸imageView

第三个contentMode应为

backgroundImage.contentMode =.scaleToFill // or .scaleAspectFill

应该提到的是,您可以将imageView添加到self.view中,并使scrollView背景透明,以避免拉伸导致的imageView质量和外观损失

相关问题