package com.yidianling.course.widget

import android.content.Context
import android.support.v4.view.ViewPager
import android.view.View
import com.yidianling.common.tools.RxImageTool


/**
 * @author jiucheng
 * @描述:实现ViewPager左右滑动时的时差
 * @Copyright Copyright (c) 2018
 * @Company 壹点灵
 * @date 2019/8/6
 */
class CustomPagerTransformer(var mContext: Context) : ViewPager.PageTransformer {
    private var maxTranslateOffsetX: Int = 0
    private var viewPager: ViewPager? = null

    init {
        this.maxTranslateOffsetX = RxImageTool.dp2px(40f)
    }

    override fun transformPage(view: View, position: Float) {
        if (viewPager == null) {
            viewPager = view.parent as ViewPager?
        }

        val leftInScreen = view.left - viewPager!!.scrollX
        val centerXInViewPager = leftInScreen + view.measuredWidth / 2
        val offsetX = centerXInViewPager - viewPager!!.measuredWidth / 2
        val offsetRate = offsetX.toFloat() * 0.38f / viewPager!!.measuredWidth
        val scaleFactor = 1 - Math.abs(offsetRate)
        if (scaleFactor > 0) {
            view.scaleX = scaleFactor
            view.scaleY = scaleFactor
            view.translationX = -maxTranslateOffsetX * offsetRate
        }
    }
}