UIScrollview bounce and zoom with fixed top

2019-05-24 05:24发布

问题:

Trying to make UIImageView scale when the scrollview is bouncing down.

The idea was stolen from this dribbble: https://dribbble.com/shots/3341878-Product-Page

As you can see, image is like'a scaling when the scrollview is bouncing down.

In my app I have the UIImageView inside the UIScrollview, I can't understand how to fix the top of the UIImageView while the UIScrolvview is bouncing down.

Here is what I want to do:

回答1:

Apply a scale transform to your imageView based on your scrollview's offset. Something along those lines:

extension ViewController: UIScrollViewDelegate {
    public func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let offset = scrollView.contentOffset

        if offset.y < 0.0 {
            var transform = CATransform3DTranslate(CATransform3DIdentity, 0, offset.y, 0)
            let scaleFactor = 1 + (-1 * offset.y / (imageViewHeightConstraint.constant / 2))
        transform = CATransform3DScale(transform, scaleFactor, scaleFactor, 1)
            imageView.layer.transform = transform
        } else {
            imageView.layer.transform = CATransform3DIdentity
        }
    }
}

In this way you don't need to "fix" it to top, the imageView will simply scale up as the content offset decreases when bouncing. All you need is that your imageView has a top constraint (plus leading, trailing) and a height.



回答2:

I recommend you to use one of the following libraries

MXParallaxHeader

StrechyParallaxScrollView



回答3:

You can 'cheat' by placing the image above the scrollview and set its height in the didScroll method on you scrollviewdelegate (read content offset and determine image height). If you set the image to aspect fill it will have the effect you want.