Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 滑動效果進階(六):打造圖片倒影效果

編輯:Android 開發教學

上一篇介紹了用 Animation 實現 3D 旋轉翻頁,這次來說明如何製作圖片倒影,先看效果圖:

本示例主要透過自定義 Gallery 與 ImageAdapter(繼承自 BaseAdapter)實現。

1. 倒影繪製

倒影原理:倒影效果主要由「原圖+間距+倒影」三部分組成,總高度約為原圖的 3/2(原圖為 1、倒影為 1/2)。原圖就是最上方看到的圖片;間距是原圖與倒影之間的縫隙(如 reflectionGap = 4);倒影則是原圖下半部 1/2 的高度,透過矩陣變換 matrix.preScale(1, -1) 取得倒立圖片,再加上線性遮罩與陰影呈現。

倒影實作程式碼:

 /** 反射倒影 */ public boolean createReflectedImages() { final int reflectionGap = 4; int index = 0; for (Map<String, Object> map : list) { Integer id = (Integer) map.get("image"); Bitmap originalImage = BitmapFactory.decodeResource(mContext.getResources(), id); // 獲取原始圖片 int width = originalImage.getWidth(); int height = originalImage.getHeight(); 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); // 創建倒影圖片(高度為原圖3/2) Canvas canvas = new Canvas(bitmapWithReflection); // 繪制倒影圖(原圖 + 間距 + 倒影) canvas.drawBitmap(originalImage, 0, 0, null); // 繪制原圖 Paint paint = new Paint(); canvas.drawRect(0, height, width, height + reflectionGap, paint); // 繪制原圖與倒影的間距 canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null); // 繪制倒影圖 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 myGallery.LayoutParams(180, 240)); imageView.setScaleType(ScaleType.MATRIX); mImages[index++] = imageView; } return true; }

透過 createBitmap 的矩陣翻轉搭配 LinearGradient 線性遮罩,就能自然呈現由實到透的倒影漸層效果。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved