編輯:關於 Android 程式設計
用過 Android 自帶 Gallery 組件的人都知道,它能做的只是橫向拖動瀏覽一組圖片,和 iPhone 上那種帶景深效果的 Coverflow 比起來差距明顯。但其實只要擴展 Gallery,借助偽 3D 變換,就能做出相當接近的視覺效果。本文通過源碼拆解整個實現過程。
第一步:為圖片製作倒影
使用 Gallery 必須先提供一個 Adapter。這裡我們自定義 ImageAdapter,在構造時傳入 Context 和圖片資源 ID 數組,然後調用 createReflectedImages() 為每張圖生成倒影,最後在 getView() 中返回對應的 ImageView。
public class ImageAdapter extends BaseAdapter {
int mGalleryItemBackground;
private Context mContext;
private Integer[] mImageIds;
private ImageView[] mImages;
public ImageAdapter(Context c, int[] ImageIds) {
mContext = c;
mImageIds = ImageIds;
mImages = new ImageView[mImageIds.length];
}
public boolean createReflectedImages() {
// 原圖與倒影之間的間距
final int reflectionGap = 4;
int index = 0;
for (int imageId : mImageIds) {
Bitmap originalImage = BitmapFactory.decodeResource(
mContext.getResources(), imageId);
int width = originalImage.getWidth();
int height = originalImage.getHeight();
// 沿 Y 軸翻轉矩陣
Matrix matrix = new Matrix();
matrix.preScale(1, -1);
// 只取下半部分並翻轉,作為倒影
Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0,
height / 2, width, height / 2, matrix, false);
// 新建一張更高的位圖,容納原圖 + 間距 + 倒影
Bitmap bitmapWithReflection = Bitmap.createBitmap(width,
(height + height / 2), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmapWithReflection);
canvas.drawBitmap(originalImage, 0, 0, null);
// 畫間距
Paint deafaultPaint = new Paint();
canvas.drawRect(0, height, width, height + reflectionGap, deafaultPaint);
// 畫倒影
canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);
// 用線性漸變給倒影做淡出效果
Paint paint = new Paint();
LinearGradient shader = new LinearGradient(0, originalImage.getHeight(),
0, bitmapWithReflection.getHeight() + reflectionGap,
0x70ffffff, 0x00ffffff, TileMode.CLAMP);
paint.setShader(shader);
paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
canvas.drawRect(0, height, width,
bitmapWithReflection.getHeight() + reflectionGap, paint);
ImageView imageView = new ImageView(mContext);
imageView.setImageBitmap(bitmapWithReflection);
imageView.setLayoutParams(new GalleryFlow.LayoutParams(160, 240));
mImages[index++] = imageView;
}
return true;
}
public int getCount() {
return mImageIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
return mImages[position];
}
/**
* 根據距離中心的偏移量計算縮放比例
* 公式:1 / (2 ^ offset)
*/
public float getScale(boolean focused, int offset) {
return Math.max(0, 1.0f / (float) Math.pow(2, Math.abs(offset)));
}
}
第二步:擴展 Gallery 實現旋轉與縮放
光有倒影還不夠,Coverflow 的靈魂在於圖片切換時的旋轉和遠近變化,而原生 Gallery 並未提供這能力。好在 Gallery 打開了一個入口——getChildStaticTransformation(),我們覆寫它,再結合 Camera 與 Matrix 完成偽 3D 變換即可。
public class GalleryFlow extends Gallery {
/** 用於對 ImageView 矩陣做變換的虛擬攝像機 */
private Camera mCamera = new Camera();
/** 子 View 的最大旋轉角度 */
private int mMaxRotationAngle = 60;
/** 中心圖片的最大拉近幅度 */
private int mMaxZoom = -120;
/** Coverflow 的中心位置 */
private int mCoveflowCenter;
public GalleryFlow(Context context) {
super(context);
this.setStaticTransformationsEnabled(true);
}
public GalleryFlow(Context context, AttributeSet attrs) {
super(context, attrs);
this.setStaticTransformationsEnabled(true);
}
public GalleryFlow(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.setStaticTransformationsEnabled(true);
}
public int getMaxRotationAngle() {
return mMaxRotationAngle;
}
public void setMaxRotationAngle(int maxRotationAngle) {
mMaxRotationAngle = maxRotationAngle;
}
public int getMaxZoom() {
return mMaxZoom;
}
public void setMaxZoom(int maxZoom) {
mMaxZoom = maxZoom;
}
/** 計算 Coverflow 中心 */
private int getCenterOfCoverflow() {
return (getWidth() - getPaddingLeft() - getPaddingRight()) / 2 + getPaddingLeft();
}
/** 計算某個 View 的中心 */
private static int getCenterOfView(View view) {
return view.getLeft() + view.getWidth() / 2;
}
@Override
protected boolean getChildStaticTransformation(View child, Transformation t) {
final int childCenter = getCenterOfView(child);
final int childWidth = child.getWidth();
int rotationAngle = 0;
t.clear();
t.setTransformationType(Transformation.TYPE_MATRIX);
if (childCenter == mCoveflowCenter) {
transformImageBitmap((ImageView) child, t, 0);
} else {
rotationAngle = (int) (((float) (mCoveflowCenter - childCenter) / childWidth)
* mMaxRotationAngle);
if (Math.abs(rotationAngle) > mMaxRotationAngle) {
rotationAngle = (rotationAngle < 0) ? -mMaxRotationAngle : mMaxRotationAngle;
}
transformImageBitmap((ImageView) child, t, rotationAngle);
}
return true;
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
mCoveflowCenter = getCenterOfCoverflow();
super.onSizeChanged(w, h, oldw, oldh);
}
/**
* 按指定角度對圖片做變換
*/
private void transformImageBitmap(ImageView child, Transformation t, int rotationAngle) {
mCamera.save();
final Matrix imageMatrix = t.getMatrix();
final int imageHeight = child.getLayoutParams().height;
final int imageWidth = child.getLayoutParams().width;
final int rotation = Math.abs(rotationAngle);
// 沿 Z 軸正向移動視角,效果相當於放大圖片
// 若在 Y 軸移動則圖片上下位移,X 軸則左右位移
mCamera.translate(0.0f, 0.0f, 100.0f);
// 角度越小(越靠近中心),拉近越多
if (rotation < mMaxRotationAngle) {
float zoomAmount = (float) (mMaxZoom + (rotation * 1.5));
mCamera.translate(0.0f, 0.0f, zoomAmount);
}
// 繞 Y 軸旋轉,形成豎向翻轉的縱深感
mCamera.rotateY(rotationAngle);
mCamera.getMatrix(imageMatrix);
imageMatrix.preTranslate(-(imageWidth / 2), -(imageHeight / 2));
imageMatrix.postTranslate((imageWidth / 2), (imageHeight / 2));
mCamera.restore();
}
}
調用方式
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_gallery);
Integer[] images = {
R.drawable.img0001, R.drawable.img0030, R.drawable.img0100,
R.drawable.img0130, R.drawable.img0200, R.drawable.img0230,
R.drawable.img0300, R.drawable.img0330, R.drawable.img0354
};
ImageAdapter adapter = new ImageAdapter(this, images);
adapter.createReflectedImages();
GalleryFlow galleryFlow = (GalleryFlow) findViewById(R.id.gallery_flow);
galleryFlow.setAdapter(adapter);
}
幾個實踐補充
關於鋸齒:直接用 setImageBitmap 顯示時鋸齒比較明顯,改用 Drawable 並開啟抗鋸齒能大幅改善:
BitmapDrawable bd = new BitmapDrawable(bitmapWithReflection); bd.setAntiAlias(true); iv.setImageDrawable(bd);
關於內存:ImageAdapter 存在潛在的內存洩露風險,BitmapFactory 的解碼對象若不及時釋放,反覆旋轉屏幕可能誘發 OOM。可以嘗試在使用完畢後調用 recycle() 並置空引用,同時及時觸發 GC。這個問題在 Google Group 上有過充分討論,一般主要出現在 debug 模式下。
關於抗鋸齒為何不默認開啟:鋸齒無法被完全消除,抗鋸齒的本質是通過插值計算相鄰像素的相關度、插入中間色以平滑邊緣,這必然要付出額外的運算開銷。據粗略估計,開啟後圖形性能可能下降三成以上。在這個場景中圖形運算並不複雜,所以影響有限,但在模擬器或低端真機上測試時差異就會顯現出來。
關於 preTranslate 與 postTranslate:這兩行代碼決定變換的中心點在哪裡。
imageMatrix.preTranslate(-(imageWidth / 2), -(imageHeight / 2)); imageMatrix.postTranslate((imageWidth / 2), (imageHeight / 2));
preTranslate 在後續所有矩陣變換之前執行,postTranslate 則在之後執行。兩者合起來的效果是:變換前先把坐標系原點移到圖像中心,變換完成後再移回去。加上它們,所有變換都以圖像中心為軸;不加,則以左上角原點為軸。就像一根棍子,握著一端旋轉和握著中間旋轉,畫出來的軌跡完全不同。本質上就是矩陣變換中「變換中心」的常規處理手法。
把 these 參數(旋轉角度、縮放幅度、間距、尺寸)按自己的設計稿調一調,還能延伸出更多花樣的效果。
Android 直播與音視頻播放入門
音視頻越來越熱,教育、遊戲、娛樂、體育、餐飲、音樂等各個領域都在嘗試直播或點播。對剛入門的開發者來說,如何快速建立音視頻基礎認知、理清編解碼與傳輸協議、做好技術選型、避開
Android相冊瀑布流照片牆實作解析
傳統網格布局雖然整齊,但當圖片尺寸不一致時,容易出現空白或裁切問題。瀑布流布局則能讓不同高度的圖片自然排列,視覺上更活潑,也常用於相冊、商品列表與社群照片牆。 瀑布流的基
DrySister 看妹子應用(第二版):解析後台接口數據
一、上節回顧與本節目標 上一節我們把項目骨架搭了起來,並托管到了 GitHub。復盤之後,有兩處明顯需要改進: 1. 圖片 URL 目前是寫死的 → 改為解析接口返回的
Android 自訂 3D 畫廊與圖像矩陣原理
3D 畫廊的視覺效果Android 內建的 Gallery 可以展示圖片,但效果較為平面。若想加入立體感、旋轉、遠近與倒影,可以自訂 Gallery,並透過 Camera