寺庫app的廣告,最近在地鐵滿天飛,打開app看了看,有個頁面比較炫,遂拿來模仿一番,先來簡單看看
寺庫實(shí)現(xiàn)的效果。

sicoo.gif
這個是模仿的效果,因?yàn)橄矚g海賊王,所以素材當(dāng)然是我草帽海賊團(tuán)全員。

luffy.gif
實(shí)現(xiàn)原理:
1、自定義imageView,添加doTranslate方法。
2、抽象類ParallaxViewHolder并實(shí)現(xiàn)接口ParallaxImageListener,暴露方法animateImage,實(shí)時調(diào)用doTranslate方法。
3、自定義RecycleView,添加滾動監(jiān)聽addOnScrollListener,滾動監(jiān)聽觸發(fā)時會調(diào)用animateImage不斷改變imagView的顯示范圍。
核心:
代碼已經(jīng)提交github,具體實(shí)現(xiàn)細(xì)節(jié)可以參考demo中的代碼。這里只列出核心代碼。
github地址:https://github.com/daimaXZ/sicooDemo
demo下載地址:http://fir.im/sicoo
自定義ImageView
//doTranslate中調(diào)用getValues獲取單個item和RecycleView的高度及坐標(biāo)點(diǎn)
private boolean getValues() {
int[] values = getListener().requireValuesForTranslate();
if (values == null)
return false;
this.rowHeight = values[0];
this.rowYPos = values[1];
this.recyclerViewHeight = values[2];
this.recyclerViewYPos = values[3];
return true;
}
private void calculateAndMove() {
//item rowYPos距離中間點(diǎn)的位置
float distanceFromCenter = (recyclerViewYPos + recyclerViewHeight) / 2 - rowYPos;
//圖片單位像素值
int imageHeight = getDrawable().getIntrinsicHeight();
float scale = 1;
if (shouldCenterCrop) {
scale = recomputeImageMatrix();
imageHeight *= scale;
//centerCrop之后圖片的高度
}
//圖片可以滑動的距離范圍
float difference = imageHeight - rowHeight;
//item在recyclerView中的滾動距離
float move = (distanceFromCenter / recyclerViewHeight) * difference * parallaxValue;
//ImageView需要移動到位置
float translate = (move - difference)/ 2;
//以上兩行代碼,如果有能解釋清楚地,歡迎評論!
moveTo(translate, scale);
}
/**
*計算scale值
* @return
*/
private float recomputeImageMatrix() {
float scale;
final int viewWidth = getWidth() - getPaddingLeft() - getPaddingRight();
final int viewHeight = getHeight() - getPaddingTop() - getPaddingBottom();
final int drawableWidth = getDrawable().getIntrinsicWidth();
final int drawableHeight = getDrawable().getIntrinsicHeight();
if (drawableWidth * viewHeight > drawableHeight * viewWidth) {
scale = (float) viewHeight / (float) drawableHeight;
} else {
scale = (float) viewWidth / (float) drawableWidth;
}
return scale;
}
private void moveTo(float move, float scale) {
//利用矩陣進(jìn)行圖片的縮放和位移
Matrix imageMatrix = getImageMatrix();
if (scale != 1) {
// 先對圖片進(jìn)行比例縮放
imageMatrix.setScale(scale, scale);
}
float[] matrixValues = new float[9];
imageMatrix.getValues(matrixValues);
float current = matrixValues[Matrix.MTRANS_Y];
// 圖片水平垂直移動
imageMatrix.postTranslate(0, move - current);
setImageMatrix(imageMatrix);
invalidate();
}
另外還寫了一個viewpager的滑動視差,和開眼視頻還有最近騰訊新出的一款本地音樂app(輕聽)一樣的效果。有興趣的朋友,也就可以去看看:
github地址: https://github.com/daimaXZ/ParallaxDemo
demo下載地址:http://fir.im/ParallaxDemo
效果圖:

ParallaxDemo.gif
以上!希望各位大大喜歡!
Thanks yayaa!