一、需求分析
PageTransformer非常方便的提供了ViewPager页面之间的切换,最近有个需求和交通银行类似,实现3D翻转,说到3D翻转我们下意识的可能想到的是Camera+Matrix错切动画,实际上这也是可行的一种方案,我们在dispatchDraw的时候,旋转canvas即可,但是实现也相对来说比较复杂。我们可以更简单的方式来实现。
二、效果
当参数未30度旋转时
当参数为90度旋转
三、代码实现
public class Rotation3DPageTransformer implements ViewPager.PageTransformer {
private float degree = 30;
public Rotation3DPageTransformer(float degree) {
this.degree = degree>0?Math.min(degree,90) : Math.max(degree,90);
}
private int computPivotX(View page, float position) {
if (position > 0 && position <= 1) {
return 0;
} else if (-1 < position && position <= 0) {
return page.getWidth();
}
return -1;
}
@Override
public void transformPage(View page, float position) {
Object tag = page.getTag();
Log.e(String.valueOf(tag), position + "");
/*
* 左2 左侧页面(左1) 当前页面 右侧页面(右1) 右2
* 左滑: -3 <- -2 -2 <- -1 -1 <- 0 0 <- 1 1 <- 2
*
* 右滑: -2 -> -1 -1 -> 0 0 -> 1 1 -> 2 2 -> 3
*
*/
int pivotX = computPivotX(page, position);
if (pivotX < 0) {
return;
}
page.setPivotX(pivotX);
page.setRotationY(degree * position);
}
}