Skip to content

Instantly share code, notes, and snippets.

@OmarKRostom
Created October 19, 2020 05:59
Show Gist options
  • Save OmarKRostom/f4c12b251ebd9cf3b8e325ec565a1363 to your computer and use it in GitHub Desktop.
Save OmarKRostom/f4c12b251ebd9cf3b8e325ec565a1363 to your computer and use it in GitHub Desktop.
A recyclerview to apply the scaling effect on scrolling
import android.animation.ArgbEvaluator
import android.content.Context
import android.graphics.ColorMatrix
import android.graphics.ColorMatrixColorFilter
import android.util.AttributeSet
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.omvana.mixer.R
import kotlin.math.pow
class HorizontalCarouselRecyclerView(context: Context, attrs: AttributeSet) : RecyclerView(context, attrs) {
fun <T : ViewHolder> initialize(newAdapter: Adapter<T>) {
layoutManager = ArcLayoutManager(context, HORIZONTAL)
newAdapter.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() {
override fun onChanged() {
post {
addOnScrollListener(object : OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
onScrollChanged()
}
})
}
}
})
adapter = newAdapter
}
private fun onScrollChanged() {
post {
(0 until childCount).forEach { position ->
val child = getChildAt(position)
val childCenterX = (child.left + child.right) / 2
val scaleValue = getGaussianScale(childCenterX, 0.8f, 0.2f, 150.toDouble())
child.scaleX = scaleValue
child.scaleY = scaleValue
}
}
}
private fun getGaussianScale(
childCenterX: Int,
minScaleOffest: Float,
scaleFactor: Float,
spreadFactor: Double
): Float {
val recyclerCenterX = (left + right) / 2
return (Math.E.pow(-(childCenterX - recyclerCenterX.toDouble()).pow(2.toDouble()) / (2 * spreadFactor.pow(2.toDouble()))) * scaleFactor + minScaleOffest).toFloat()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment