如何使背景图像正确适合滚动视图?
Posted
技术标签:
【中文标题】如何使背景图像正确适合滚动视图?【英文标题】:How to make background image fit properly in scroll view? 【发布时间】:2018-09-11 17:44:43 【问题描述】:scaleAspectfit 似乎不起作用。我试图让我的整个背景图像稍微适合背景,看到更多的图像。我添加了一个滚动视图,以便用户可以上下滚动一点来查看图像。
但是,我的应用太放大了图像。
lazy var scrollView: UIScrollView =
let view = UIScrollView()
view.translatesAutoresizingMaskIntoConstraints = false
view.contentSize.height = 800
view.bounces = true
return view
()
覆盖 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
【问题讨论】:
【参考方案1】:首先您在此处的 2 个地方添加相同的 imageView
view.insertSubview(backgroundImage, at: 0)
这里
scrollView.addSubview(backgroundImage)
所以最终它只会被添加到滚动视图中,因为它是一个对象
其次你需要像这样约束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)
然后imageView会根据scrollView的内容进行拉伸
第三个contentMode
应该是
backgroundImage.contentMode =.scaleToFill // or .scaleAspectFill
应该提一下,可以将imageView添加到self.view
,并使scrollView背景透明,避免拉伸导致imageView失去质量和方面
【讨论】:
我实际上最终在 swift 之外缩放了我的图片以正确适应应用程序,但您的回答帮助我了解了更多滚动和视图。谢谢以上是关于如何使背景图像正确适合滚动视图?的主要内容,如果未能解决你的问题,请参考以下文章
ContentView (SwiftUI) 的背景图像不是子视图,但具有正确的滚动行为