編輯:Android 技術基礎
前面兩節我們學了 Bitmap,以及繪圖 API 的一些屬性和常用方法,但光看不做總覺得踏實不起來。本節安排兩個小專案,把知識落地:
- 1. 自製一個簡單的塗鴉畫板
- 2. 用像素操作做「刮開看背後圖片」的效果
第二個例子是很經典的像素操作練習,正好可以對照第一節那種「方塊擦除」的粗糙做法,看看差別在哪。開始今天的內容。
這個大家都不陌生,很多手機都內建一塊給使用者塗鴉的畫板。動手之前,先把幾個關鍵問題想清楚。
Q1:畫在哪裡?
答:畫在 View 裡。我們自訂一個 View,在 onDraw() 完成繪製;另外 View 本身有 onTouchEvent(),正好用來取得使用者的手勢。
Q2:需要準備什麼?
答:一支畫筆(Paint)、一塊畫布(Canvas)、一條記錄軌跡的路徑(Path)。這裡有個坑:每次畫線其實只是「從上一個觸點連到這一觸點」,如果直接畫在 Canvas 上,之前的筆跡就會被清掉。解法是所謂的雙緩衝技術——先把內容畫到一張 Bitmap 上,累積完成後再整張貼到 View,這樣之前的筆跡自然保留。
Q3:流程怎麼走?
答:初始化畫筆並設定顏色等參數;在 onMeasure() 建立一張與 View 同尺寸的 Bitmap 與對應的 Canvas;在 onTouchEvent 取得 X、Y 座標並往 Path 上連線,最後呼叫 invalidate() 觸發 onDraw,把 Bitmap 畫到畫布上。
MyView.java:
public class MyView extends View {
private Paint mPaint; // 畫筆
private Path mPath; // 記錄使用者軌跡
private Canvas mCanvas; // 記憶體中的 Canvas
private Bitmap mBitmap; // 緩存已繪製內容
private int mLastX;
private int mLastY;
public MyView(Context context) {
super(context);
init();
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
mPath = new Path();
mPaint = new Paint();
mPaint.setColor(Color.GREEN);
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND); // 轉折處圓角
mPaint.setStrokeCap(Paint.Cap.ROUND); // 線頭圓角
mPaint.setStrokeWidth(20); // 筆寬
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = getMeasuredWidth();
int height = getMeasuredHeight();
// 建立與 View 同尺寸的緩衝 Bitmap 與 Canvas
mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
}
@Override
protected void onDraw(Canvas canvas) {
drawPath();
canvas.drawBitmap(mBitmap, 0, 0, null);
}
// 把 Path 畫進緩衝區
private void drawPath() {
mCanvas.drawPath(mPath, mPaint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
int x = (int) event.getX();
int y = (int) event.getY();
switch (action) {
case MotionEvent.ACTION_DOWN:
mLastX = x;
mLastY = y;
mPath.moveTo(mLastX, mLastY);
break;
case MotionEvent.ACTION_MOVE:
int dx = Math.abs(x - mLastX);
int dy = Math.abs(y - mLastY);
// 位移太小的點直接忽略,避免 Path 節點爆炸
if (dx > 3 || dy > 3) {
mPath.lineTo(x, y);
}
mLastX = x;
mLastY = y;
break;
}
invalidate();
return true;
}
}
執行結果

這個骨架可以再往外延伸,例如加上筆粗調整、顏色切換、橡皮擦、把畫好的圖存成檔案等等。可以自己想看看還缺什麼。
核心思路:用 FrameLayout 疊兩張 ImageView,下層放「刮開後」的圖,上層放「還沒刮開」的圖;然後在上層的 ImageView 上掛 OnTouchListener,把手指經過範圍內的像素設為透明,下面的圖就露出來了。
這個做法的缺點也很明顯——擦除邊緣是方形的。下一節學完 PorterDuff 之後,我們會回頭把它改成圓形筆刷。
執行結果

Step 1:先看選圖頁。activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <ImageView android:id="@+id/img_choose" android:layout_width="320dp" android:layout_height="320dp" /> <Button android:id="@+id/btn_choose" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="開始挑戰" /> <Gallery android:id="@+id/gay_choose" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="25dp" android:spacing="1pt" android:unselectedAlpha="0.6" /> </LinearLayout>
Gallery 的 Adapter,這裡直接複寫 BaseAdapter,項目只顯示一張圖,就不另開版面配置檔了。
MeiziAdapter.java
public class MeiziAdapter extends BaseAdapter {
private Context mContext;
private int[] mData;
public MeiziAdapter() {
}
public MeiziAdapter(Context mContext, int[] mData) {
this.mContext = mContext;
this.mData = mData;
}
@Override
public int getCount() {
return mData.length;
}
@Override
public Object getItem(int position) {
return mData[position];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imgMezi = new ImageView(mContext);
imgMezi.setImageResource(mData[position]);
imgMezi.setScaleType(ImageView.ScaleType.FIT_XY);
imgMezi.setLayoutParams(new Gallery.LayoutParams(250, 250));
TypedArray typedArray = mContext.obtainStyledAttributes(R.styleable.Gallery);
imgMezi.setBackgroundResource(typedArray.getResourceId(R.styleable.Gallery_android_galleryItemBackground, 0));
typedArray.recycle();
return imgMezi;
}
}
MainActivity 也很單純:為 Gallery 掛上 onItemSelected,按下按鈕時把目前選取的 index 傳給下一頁。
MainActivity.java
public class MainActivity extends AppCompatActivity
implements AdapterView.OnItemSelectedListener, View.OnClickListener {
private Context mContext;
private ImageView img_choose;
private Button btn_choose;
private Gallery gay_choose;
private int index = 0;
private MeiziAdapter mAdapter = null;
private int[] imageIds = new int[] {
R.mipmap.pre1, R.mipmap.pre2, R.mipmap.pre3, R.mipmap.pre4, R.mipmap.pre5,
R.mipmap.pre6, R.mipmap.pre7, R.mipmap.pre8, R.mipmap.pre9, R.mipmap.pre10,
R.mipmap.pre11, R.mipmap.pre12, R.mipmap.pre13, R.mipmap.pre14, R.mipmap.pre15,
R.mipmap.pre16, R.mipmap.pre17, R.mipmap.pre18, R.mipmap.pre19, R.mipmap.pre20,
R.mipmap.pre21
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = MainActivity.this;
bindViews();
}
private void bindViews() {
img_choose = (ImageView) findViewById(R.id.img_choose);
btn_choose = (Button) findViewById(R.id.btn_choose);
gay_choose = (Gallery) findViewById(R.id.gay_choose);
mAdapter = new MeiziAdapter(mContext, imageIds);
gay_choose.setAdapter(mAdapter);
gay_choose.setOnItemSelectedListener(this);
btn_choose.setOnClickListener(this);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
img_choose.setImageResource(imageIds[position]);
index = position;
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
@Override
public void onClick(View v) {
Intent it = new Intent(mContext, CaClothes.class);
Bundle bundle = new Bundle();
bundle.putCharSequence("num", Integer.toString(index));
it.putExtras(bundle);
startActivity(it);
}
}
Step 2:刮圖頁面。activity_caclothes.xml,FrameLayout 疊兩層 ImageView:
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:id="@+id/img_after" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <ImageView android:id="@+id/img_before" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </FrameLayout>
CaClothes.java
public class CaClothes extends AppCompatActivity implements View.OnTouchListener {
private ImageView img_after;
private ImageView img_before;
private Bitmap alterBitmap; // 可修改的副本
private Canvas canvas;
private Paint paint;
private Bitmap after;
private Bitmap before;
private int position;
int[] imageIds1 = new int[] {
R.mipmap.pre1, R.mipmap.pre2, R.mipmap.pre3, R.mipmap.pre4, R.mipmap.pre5,
R.mipmap.pre6, R.mipmap.pre7, R.mipmap.pre8, R.mipmap.pre9, R.mipmap.pre10,
R.mipmap.pre11, R.mipmap.pre12, R.mipmap.pre13, R.mipmap.pre14, R.mipmap.pre15,
R.mipmap.pre16, R.mipmap.pre17, R.mipmap.pre18, R.mipmap.pre19, R.mipmap.pre20,
R.mipmap.pre21
};
int[] imageIds2 = new int[] {
R.mipmap.after1, R.mipmap.after2, R.mipmap.after3, R.mipmap.after4, R.mipmap.after5,
R.mipmap.after6, R.mipmap.after7, R.mipmap.after8, R.mipmap.after9, R.mipmap.after10,
R.mipmap.after11, R.mipmap.after12, R.mipmap.after13, R.mipmap.after14, R.mipmap.after15,
R.mipmap.after16, R.mipmap.after17, R.mipmap.after18, R.mipmap.after19, R.mipmap.after20,
R.mipmap.after21
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_caclothes);
Bundle bd = getIntent().getExtras();
position = Integer.parseInt(bd.getString("num"));
bindViews();
}
private void bindViews() {
img_after = (ImageView) findViewById(R.id.img_after);
img_before = (ImageView) findViewById(R.id.img_before);
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = 1;
after = BitmapFactory.decodeResource(getResources(), imageIds2[position], opts);
before = BitmapFactory.decodeResource(getResources(), imageIds1[position], opts);
// 建立一份可寫入的副本,原圖保持唯讀
alterBitmap = Bitmap.createBitmap(before.getWidth(), before.getHeight(), Bitmap.Config.ARGB_4444);
canvas = new Canvas(alterBitmap);
paint = new Paint();
paint.setStrokeCap(Paint.Cap.ROUND);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeWidth(5);
paint.setColor(Color.BLACK);
paint.setAntiAlias(true);
canvas.drawBitmap(before, new Matrix(), paint);
img_after.setImageBitmap(after);
img_before.setImageBitmap(before);
img_before.setOnTouchListener(this);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE:
int newX = (int) event.getX();
int newY = (int) event.getY();
// setPixel 把單一像素設為指定顏色,這裡設成透明
// 用雙層迴圈把手指周圍 40x40 的方塊範圍清成透明
for (int i = -20; i < 20; i++) {
for (int j = -20; j < 20; j++) {
if (i + newX >= 0 && j + newY >= 0
&& i + newX < before.getWidth() && j + newY < before.getHeight()) {
alterBitmap.setPixel(i + newX, j + newY, Color.TRANSPARENT);
}
}
}
img_before.setImageBitmap(alterBitmap);
break;
}
return true;
}
}
程式碼不算難懂。要注意的兩個細節:一是必須先複製一份可寫的 Bitmap,原圖不可改;二是 setPixel 是逐點操作,迴圈範圍越大就越耗效能,正式專案裡應該改用 Path 或 Bitmap 搭配 PorterDuff 來做。
DrawDemo1.zip(含大量圖片素材,檔案約 20 多 MB)
本節寫了兩個繪圖小專案:塗鴉畫板與刮開圖片效果。前者練 Path 與雙緩衝,後者練像素操作,都是自訂 View 的常見套路。
你也會注意到刮除邊緣是方的,看起來不太精緻。下一節學完 PorterDuff 之後,我們會把這個效果升級成圓形筆刷,程式碼反而更短。另外基於時間考量,範例程式碼沒有特別整理優化,建議依自己的需求再調整。就聊到這裡。
Android 觸摸事件:OnTouchListener、OnTouchEvent 與多點觸碰
OnTouchListener 與 OnTouchEvent 的差異 Android 的觸摸處理有兩種常見方式:OnTouchListener 是監聽模式,通常附加在 V
Button 與 ImageButton:StateListDrawable 與水波效果
本節引言: 這一節介紹兩個按鈕控件:Button(普通按鈕)和 ImageButton(圖像按鈕)。兩者用法基本類似,圖片相關部分則和後面的 ImageView 相同,所
從零開始學 Android:Bitmap 圖像處理入門
用 BitmapFactory 載入圖片 Android 顯示圖片的方式很多,最基礎的做法之一,是用 BitmapFactory.decodeResource 從資源中取
Android 網路編程入門與 HTTP 協議完全解析
本節導讀 終於來到 Android 網路編程這一關鍵章節。前面我們寫的都是單機程式,難免有些意猶未盡。從本節開始,我們正式邁入網路開發的世界。接下來要掌握的內容包括:An