Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ImageView Scaling when scrolling down

How can I simply scaling imageView with autolayout when scrolling down ?

Try to see parallax effect but not exactly what I wanted.

I just want to use a scrollView and a header ImageView who can resize depends on scrollView position.

like image 458
raphael Avatar asked Nov 29 '22 23:11

raphael


1 Answers

Step by Step:

1 - open storyboard and add an image view on top with these constraint (choose your aspect ratio) :

enter image description here

2 - select aspectFill mode and clipSubviews for your uiimage

3 - add a UIScrollView on top of your viewController with a child view inside. All the details about the auto layout with scrollView : http://natashatherobot.com/ios-autolayout-scrollview/

4 - then make outlets reference of your imageView and scrollView in your code.

5 - in viewDidLoad, insert self.automaticallyAdjustsScrollViewInsets = false and set contentInsets and contentOffset of the scrollView :

class ViewController: UIViewController {

    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var imageView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.automaticallyAdjustsScrollViewInsets = false
   }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        let imageHeight = imageView.frame.height

        let newOrigin = CGPoint(x: 0, y: -imageHeight)

        scrollView.contentOffset = newOrigin
        scrollView.contentInset = UIEdgeInsets(top: imageHeight, left: 0, bottom: 0, right: 0)
    }

}

6 - add scrollviewDelegate to the ViewController and the scrollViewDidScroll method to get position of the scrollView

class ViewController: UIViewController, UIScrollViewDelegate

override func viewDidLoad() {
        super.viewDidLoad()

        scrollView.delegate = self
        self.automaticallyAdjustsScrollViewInsets = false
}

func scrollViewDidScroll(scrollView: UIScrollView) {

    let offsetY = scrollView.contentOffset.y

    if offsetY < 0
    {
        imageView.frame.size.height = -offsetY
    }
    else
    {
        imageView.frame.size.height = imageView.frame.height
    }
}

7 - then build and run.

you can download example on github: https://github.com/raphrel/scalingImageWhenScrollDown

there is maybe a better solution but this one works. enjoy

like image 143
raphael Avatar answered Dec 10 '22 10:12

raphael