Android Custom View Tutorial: Scroll Parallax Image View

Welcome back, now I want to explain about how to create a parallax effect for ImageView when it’s being scrolled. Before we go any further let’s see how it’s gonna be.


The idea behind this is that we want to transform content of the ImageView when this ImageView is being scrolled. technically Canvas of the ImageView is transformed using some kind of transformation logic (in this case parallax) before rendered

So we end up with quite simple implementation of this new child of ImageView

We would extend ImageView and implement ViewTreeObserver.OnScrollChangedListener interface because we want to be informed when this view moved/scrolled on the screen.

We have a state called enableTransformer which tell if we need to transform (in this case do parallax) the canvas view or not. Also we have viewTransformer of type ViewTransformer which would do a transformation.
Here onScrollChanged() method would be called when the view scrolled and if enableTransformer is true invalidate() it, in other words do transformation and redraw the image.


Extend this class to implement any transformation we want.

Writing Vertical Parallax Effect

In this class we implement the logic to do vertical parallax transformation like in the demo animation above.

Make this ImageView always maintain aspect ratio by

override fun onAttached(view: ScrollTransformImageView) {
view.scaleType = ImageView.ScaleType.CENTER_CROP

What going on in this code?

if (imageWidth * viewHeight < viewWidth * imageHeight){ //… }, this check means that we can only moves the image/canvas vertically (parallax) when the aspect ratio of image is look like more portrait than aspect ratio of the view. why?

For example we have image 8x8 and view 6x5, and it turns out when we scale the image down to fit the size of view, there is an invisible area of image left, that means we can translate this area up & down.

But when the aspect ratio of view is more portrait (tall) we don’t have any invisible area, instead there is blank area inside a view (which is not what we want).

Writing Horizontal Parallax Effect

Horizontal parallax effect is the same as vertical just reverse the logic from vertical to horizontal