點擊 ImageSwitcher 中的縮圖後進入全螢幕畫面,用手指在圖片上滑過,滑過的地方就被「擦開」,露出底下的圖像——這就是刮刮樂式的遮罩效果。
原理其實不複雜:準備兩張圖,一張當底圖,一張疊在上面,用手指把上層擦掉,下層自然顯現。核心在於 PorterDuff 與 PorterDuffXfermode 的搭配,Android 的 API Demo 裡也有相關示範。
原始碼可於 linuxidc 的 Android 源碼集錦(2011 年 12 月)中找到對應分類。
package com.picture;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
public class RemoveClothActivity extends Activity {
private int SCREEN_W;
private int SCREEN_H;
private int imagePosition;
private MediaPlayer mp3Player;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN); // 設定全螢幕
imagePosition = getIntent().getIntExtra("imagePosition", 0);
initMP3Player();
setContentView(new MyView(this));
}
private void initMP3Player() {
mp3Player = MediaPlayer.create(RemoveClothActivity.this, R.raw.higirl);
mp3Player.setLooping(false);
}
private void playMusic() {
mp3Player.start();
}
class MyView extends View {
private Bitmap mBitmap;
private Canvas mCanvas;
private Paint mPaint;
private Path mPath;
private float mX, mY;
private static final float TOUCH_TOLERANCE = 4;
public MyView(Context context) {
super(context);
setFocusable(true);
setScreenWH();
setBackGround();
int drawableId = 0;
try {
drawableId = R.drawable.class.getDeclaredField(
"pre" + imagePosition).getInt(this);
} catch (Exception e) {
e.printStackTrace();
}
Bitmap bm = scaleBitmapFillScreen(
BitmapFactory.decodeResource(getResources(), drawableId));
seticon1Bitmap(bm);
}
private void setScreenWH() {
DisplayMetrics dm = this.getResources().getDisplayMetrics();
SCREEN_W = dm.widthPixels;
SCREEN_H = dm.heightPixels;
}
/** alpha 介於 0 與 255 之間,用來設定 bitmap 的透明度 */
private Bitmap setBitmapAlpha(Bitmap bm, int alpha) {
int[] argb = new int[bm.getWidth() * bm.getHeight()];
bm.getPixels(argb, 0, bm.getWidth(), 0, 0, bm.getWidth(), bm.getHeight());
for (int i = 0; i < argb.length; i++) {
argb[i] = ((alpha << 24) | (argb[i] & 0x00FFFFFF));
}
return Bitmap.createBitmap(argb, bm.getWidth(), bm.getHeight(), Config.ARGB_8888);
}
/** 若圖片比螢幕小,可放大填滿整個畫面 */
private Bitmap scaleBitmapFillScreen(Bitmap bm) {
return Bitmap.createScaledBitmap(bm, SCREEN_W, SCREEN_H, true);
}
private void setBackGround() {
int drawableId = 0;
try {
drawableId = R.drawable.class.getDeclaredField(
"after" + imagePosition).getInt(this);
} catch (Exception e) {
e.printStackTrace();
}
setBackgroundResource(drawableId);
}
/** 設定覆蓋在背景之上的圖層 */
private void seticon1Bitmap(Bitmap bm) {
mPaint = new Paint();
mPaint.setAlpha(0);
mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(20);
mPath = new Path();
// 轉成 mutable bitmap 才能在上面作畫
mBitmap = Bitmap.createBitmap(SCREEN_W, SCREEN_H, Config.ARGB_8888);
mCanvas = new Canvas();
mCanvas.setBitmap(mBitmap);
// 注意:參數是 bm,不是 mBitmap
mCanvas.drawBitmap(bm, 0, 0, null);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawBitmap(mBitmap, 0, 0, null);
mCanvas.drawPath(mPath, mPaint);
super.onDraw(canvas);
}
private void touch_start(float x, float y) {
mPath.reset();
mPath.moveTo(x, y);
mX = x;
mY = y;
}
private void touch_move(float x, float y) {
float dx = Math.abs(x - mX);
float dy = Math.abs(y - mY);
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
mX = x;
mY = y;
}
}
private void touch_up() {
mPath.lineTo(mX, mY);
mCanvas.drawPath(mPath, mPaint); // 把路徑提交到離屏畫布
mPath.reset(); // 重置,避免重複繪製
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touch_start(x, y);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
touch_move(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP:
touch_up();
invalidate();
playMusic();
break;
}
return true;
}
}
}
整個效果的核心只有一行:mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN))。DST_IN 的意義是「保留目標圖(上層圖)與來源形狀交集的部分」,因此用畫筆畫出來的線條,就等於把上層圖沿著手勢擦除。
另外三個細節決定成敗:一是 Paint 的 alpha 需設為 0,改由 Xfermode 決定合成結果;二是必須用 Bitmap.createBitmap 建立 mutable 的 ARGB_8888 圖,才能作為 Canvas 的繪圖目標;三是 drawBitmap 時傳入的是原圖 bm 而非 mBitmap,否則會自己畫自己。
手勢處理上,touch_move 用 TOUCH_TOLERANCE 過濾細碎抖動,並以 quadTo 畫出平滑曲線;touch_up 才把路徑真正提交到離屏畫布,避免同一段被重複繪製。
若只是單純想改透明度而不擦除,把 setBitmapAlpha 派上用場即可;它同樣是透過位移把 alpha 通道塞進 ARGB 整數裡。