編輯:關於 Android 程式設計
標準的 Gallery 是平坦地橫向捲動,而 Coverflow 那種「中間放大、兩側往後傾斜」的 3D 相簿牆,其實可以靠繼承 Gallery 並覆寫一個方法就做出來。整個效果由三個部分組成:自訂 GalleryFlow、負責產生倒影的 ImageAdapter,以及把它們組起來的 Activity。
關鍵是 setStaticTransformationsEnabled(true)——開啟之後,Gallery 在配置子 View 時就會呼叫 getChildStaticTransformation(),我們在裡面依「這個子 View 距中心的偏移」決定它的旋轉角度與縮放量。
public class GalleryFlow extends Gallery {
private Camera mCamera = new Camera(); // 負責透視變換
private int mMaxRotationAngle = 60; // 最大旋轉角度
private int mMaxZoom = -300; // 最大縮放量
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);
}
private int getCenterOfCoverflow() {
return (getWidth() - getPaddingLeft() - getPaddingRight()) / 2 + getPaddingLeft();
}
private static int getCenterOfView(View view) {
return view.getLeft() + view.getWidth() / 2;
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
mCoveflowCenter = getCenterOfCoverflow();
super.onSizeChanged(w, h, oldw, oldh);
}
// 控制 Gallery 中每張圖片的旋轉
@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;
}
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 軸正向移動 = 把視角拉遠(圖片變小)
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);
}
mCamera.rotateY(rotationAngle); // 繞 Y 軸旋轉 = 向內翻
mCamera.getMatrix(imageMatrix);
// 以圖片中心為軸心
imageMatrix.preTranslate(-(imageWidth / 2), -(imageHeight / 2));
imageMatrix.postTranslate((imageWidth / 2), (imageHeight / 2));
mCamera.restore();
}
}
Camera 的三個軸向要記牢:Z 軸位移對應放大縮小,Y 軸旋轉對應「上下邊往內翻」,X 軸旋轉則是「左右邊往內翻」。Coverflow 用的是 Y 軸。
倒影不是另一個 View,而是直接在 createReflectedImages() 裡把「原圖 + 倒影」合成一張新的 Bitmap,順便套上漸層遮罩讓倒影自然淡出。
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private Integer[] mImageIds;
private ImageView[] mImages;
public ImageAdapter(Context c, Integer[] 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);
canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);
// 用 LinearGradient + DST_IN 讓倒影上淡下深
Paint paint = new Paint();
paint.setAntiAlias(false);
LinearGradient shader = new LinearGradient(0, originalImage.getHeight(),
0, bitmapWithReflection.getHeight() + reflectionGap,
0x70ffffff, 0x00ffffff, TileMode.MIRROR);
paint.setShader(shader);
paint.setXfermode(new PorterDuffXfermode(
android.graphics.PorterDuff.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(300, 400));
mImages[index++] = imageView;
}
return true;
}
@Override public int getCount() { return mImageIds.length; }
@Override public Object getItem(int position) { return position; }
@Override public long getItemId(int position) { return position; }
@Override public View getView(int position, View convertView, ViewGroup parent) {
return mImages[position];
}
}
這裡有個值得理解的細節:PorterDuff.Mode.DST_IN 代表「保留目標圖像與來源圖像交集處,並以來源的不透明度相乘」。搭配一個從 0x70ffffff(半透明白)漸變到 0x00ffffff(全透明)的 LinearGradient,倒影下半部就被逐渐削去,看起來像消失在水面。這比手動逐列調整 alpha 簡潔得多。
public class Gallery3DActivity extends Activity {
@Override
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.img0330, R.drawable.img0354
};
ImageAdapter adapter = new ImageAdapter(this, images);
adapter.createReflectedImages(); // 先產生倒影
GalleryFlow galleryFlow = (GalleryFlow) findViewById(R.id.Gallery01);
galleryFlow.setFadingEdgeLength(0);
galleryFlow.setSpacing(-100); // 負值讓圖片互相重疊
galleryFlow.setAdapter(adapter);
galleryFlow.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
String.valueOf(position), Toast.LENGTH_SHORT).show();
}
});
galleryFlow.setSelection(4); // 預設停在第 5 張
}
}
setSpacing(-100) 是 Coverflow 觀感的另一半:負間距讓相鄰圖片彼此重疊,配合旋轉才會產生「一疊卡片」的層次。
這份程式有明確的時代記號:Gallery 在 API 14 就被標記為 deprecated,官方建議改用 HorizontalScrollView 或 RecyclerView 自行實作。原因是 Gallery 對鍵盤、D-pad 與無障礙操作的支援有先天限制。
不過裡面的數學與 Camera 用法完全沒有過時。今天的做法是把同樣的邏輯搬到 RecyclerView.LayoutManager 上——覆寫 scrollVerticallyBy() 攔下捲動位移,再對每個可見子 View 依它與中心的距離呼叫 setTranslationZ() 與 setRotationY()。API 21 之後甚至不必再用 Camera,直接給 View 加上 setCameraDistance() 就能得到透視感。
另外,倒影那段的 Bitmap.createBitmap() 會為每張圖配置三份記憶體(原圖、倒影、合成圖)。清單一大就會有壓力,實作時應在 Activity 銷毀時 recycle,或改用 RenderScriptEffect / RenderEffect 在 GPU 上完成,成本會低很多。
Android 自定義 View 實作:可觸控互動的基金走勢圖表
這陣子在整理一套可重複使用的圖表元件,目標是做出一個支援手勢互動的基金走勢圖。完成後會把它整包收進既有的 UI 框架裡,讓其他頁面直接取用。 先看最終成品的效果: 整
Android 技術精髓:Timing Activity 即時顯示當前時間
Timing Activity 顧名思義,Timing Activity 是在 Activity 中透過執行緒通信即時顯示當前時間的範例,主要運用到 Handler 與
源碼角度深入理解 IntentService 與 HandlerThread
IntentService 是 Service 的子類別,所以它是正宗的 Service。它之所以好用,是因為背後借力於 HandlerThread。本文先從實驗出發觀察
Android Shape 詳解:用 XML 輕鬆定義矩形、圓形、漸變與描邊背景
說白了,shape 就是用來在 XML 文件裡定義各種形狀的一種手段,系統解析之後,它就能像普通 Drawable 一樣被直接使用。掌握它,能讓你在不寫一行繪製代碼的前提