Blog · 2024年8月9日 0

Android ViewPager 开发中遇到的一些画廊效果

效果1

class CustomPageTransformer : ViewPager2.PageTransformer {
    override fun transformPage(page: View, position: Float) {
        val pageWidth = page.width
        val pageHeight = page.height

        page.translationX = -position * pageWidth / 1.6f // Adjust the translation to show part of the next page

        // Scale adjustments
        val scaleFactor = if (position < 0) 1 + 0.1f * position else 1 - 0.1f * position
        page.scaleX = scaleFactor
        page.scaleY = scaleFactor

        // Adjust the translationY to align the second page's bottom with the first page's bottom
        if (position > 0) {
            val heightDiff = pageHeight * (1 - scaleFactor) / 2
            page.translationY = heightDiff
        } else {
            page.translationY = 0f
        }
    }
}