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

Android 手寫塗鴉功能實作:自定義 View 保留手寫軌跡

編輯:關於 Android 程式設計

想在一張圖片上自由塗寫,其實並不需要什麼高深技巧。核心概念只有一句話:把使用者手指走過的每一段線,持續畫在同一張 Bitmap 上,然後整張重繪。下面是一個可直接運行的完整 demo。

一、先看工程結構

二、自定義 GameView:軌跡保留的關鍵

這個 View 的做法是:在 onDraw() 中把「背景圖 + 已畫上的線」合成後一次畫出,因此每次 invalidate() 觸發重繪,先前畫過的線不會消失。

package picturegame.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import com.winton.picturegame.R;

public class GameView extends View {

    private Paint paint = null;
    private Bitmap originalBitmap = null; // 原始背景圖
    private Bitmap new1Bitmap = null;
    private Bitmap new2Bitmap = null;

    private float clickX = 0;
    private float clickY = 0;
    private float startX = 0;
    private float startY = 0;

    private boolean isMove = true;
    private boolean isClear = false;
    private int color = Color.RED;        // 預設畫筆顏色:紅色
    private float strokeWidth = 2.0f;     // 預設畫筆粗細

    public GameView(Context context) {
        this(context, null);
    }

    public GameView(Context context, AttributeSet atts) {
        this(context, atts, 0);
    }

    public GameView(Context context, AttributeSet atts, int defStyle) {
        super(context, atts, defStyle);
        originalBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.default_pic)
                .copy(Bitmap.Config.ARGB_8888, true); // 載入背景圖
        new1Bitmap = Bitmap.createBitmap(originalBitmap);
    }

    // 清除畫面
    public void clear() {
        isClear = true;
        new2Bitmap = Bitmap.createBitmap(originalBitmap);
        invalidate();
    }

    public void setStrokeWidth(float width) {
        this.strokeWidth = width;
        initPaint();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawBitmap(writer(new1Bitmap), 0, 0, null);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        clickX = event.getX();
        clickY = event.getY();
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            isMove = false;
            invalidate();
            return true;
        } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
            isMove = true;
            invalidate();
            return true;
        }
        return super.onTouchEvent(event);
    }

    /**
     * 把新畫的線段合成進 Bitmap 後回傳
     */
    public Bitmap writer(Bitmap pic) {
        initPaint();
        Canvas canvas = null;
        if (isClear) {
            canvas = new Canvas(new2Bitmap);
        } else {
            canvas = new Canvas(pic);
        }
        if (isMove) {
            canvas.drawLine(startX, startY, clickX, clickY, paint);
        }
        startX = clickX;
        startY = clickY;
        if (isClear) {
            return new2Bitmap;
        }
        return pic;
    }

    private void initPaint() {
        paint = new Paint();
        paint.setStyle(Style.STROKE);   // 畫線模式
        paint.setAntiAlias(true);       // 讓線條圓滑
        paint.setColor(color);
        paint.setStrokeWidth(strokeWidth);
    }

    // 對外開放畫筆顏色設定
    public void setColor(int color) {
        this.color = color;
        initPaint();
    }
}

三、主頁面布局

上方一排小方塊用來切換筆觸粗細,中間是畫布,下方一顆清除鈕。

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="horizontal" >

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center" >
            <TextView
                android:id="@+id/tv_30"
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:background="@drawable/bg_notifaction" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center" >
            <TextView
                android:id="@+id/tv_25"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:background="@drawable/bg_notifaction" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center" >
            <TextView
                android:id="@+id/tv_20"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:background="@drawable/bg_notifaction" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center" >
            <TextView
                android:id="@+id/tv_15"
                android:layout_width="15dp"
                android:layout_height="15dp"
                android:background="@drawable/bg_notifaction" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center" >
            <TextView
                android:id="@+id/tv_10"
                android:layout_width="10dp"
                android:layout_height="10dp"
                android:background="@drawable/bg_notifaction" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center" >
            <TextView
                android:id="@+id/tv_5"
                android:layout_width="5dp"
                android:layout_height="5dp"
                android:background="@drawable/bg_notifaction" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center" >
            <TextView
                android:id="@+id/tv_2"
                android:layout_width="2dp"
                android:layout_height="2dp"
                android:background="@drawable/bg_notifaction" />
        </LinearLayout>
    </LinearLayout>

    <picturegame.view.GameView
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:id="@+id/gameview" />

    <Button
        android:layout_width="200dp"
        android:layout_height="80dp"
        android:text="clear"
        android:textColor="@color/black"
        android:id="@+id/btn_clear" />
</LinearLayout>

四、主 Activity

package com.winton.picturegame;

import picturegame.view.GameView;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.winton.basemodule.BaseActivity;

public class MainActivity extends BaseActivity implements OnClickListener {

    private GameView gameview = null;
    private Button clear = null;
    private TextView tv30, tv25, tv20, tv15, tv10, tv5, tv2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initView() {
        setContentView(R.layout.activity_main);
        gameview = (GameView) findViewById(R.id.gameview);
        clear = (Button) findViewById(R.id.btn_clear);
        tv30 = (TextView) findViewById(R.id.tv_30);
        tv25 = (TextView) findViewById(R.id.tv_25);
        tv20 = (TextView) findViewById(R.id.tv_20);
        tv15 = (TextView) findViewById(R.id.tv_15);
        tv10 = (TextView) findViewById(R.id.tv_10);
        tv5 = (TextView) findViewById(R.id.tv_5);
        tv2 = (TextView) findViewById(R.id.tv_2);
    }

    @Override
    public void initListener() {
        clear.setOnClickListener(this);
        tv30.setOnClickListener(this);
        tv25.setOnClickListener(this);
        tv20.setOnClickListener(this);
        tv15.setOnClickListener(this);
        tv10.setOnClickListener(this);
        tv5.setOnClickListener(this);
        tv2.setOnClickListener(this);
    }

    @Override
    public void initData() {
    }

    @Override
    public void onClick(View v) {
        if (v == clear) {
            gameview.clear();
            return;
        }
        if (v == tv30) { gameview.setStrokeWidth(30f); return; }
        if (v == tv25) { gameview.setStrokeWidth(25f); return; }
        if (v == tv20) { gameview.setStrokeWidth(20f); return; }
        if (v == tv15) { gameview.setStrokeWidth(15f); return; }
        if (v == tv10) { gameview.setStrokeWidth(10f); return; }
        if (v == tv5)  { gameview.setStrokeWidth(5f);  return; }
        if (v == tv2)  { gameview.setStrokeWidth(2f);  return; }
    }
}

五、運行結果

六、一個尚未解決的問題:粗線條會斷

如圖所示,當筆觸變粗之後,線段之間會出現明顯的缺口,看起來像是一節一節的。原因不難理解:這個版本是用 drawLine() 一段一段「點到點」相連,而手指移動產生的取樣點間距在快速滑動時會被拉大,兩段線之間自然留下空隙。

可能的解法有幾個方向:

1. 改用 Path + quadTo 畫貝茲曲線,讓相鄰取樣點之間以平滑曲線銜接,這是最推薦的做法。
2. 設定 Paint.Cap.ROUND(paint.setStrokeCap(Paint.Cap.ROUND)),讓線段端點呈圓形,可以掩蓋小缺口。
3. 補插補點,在兩點距離超過門檻值時,中間插入若干虛擬點再連線。

實務上前兩者搭配使用,視覺效果就會自然許多。

以上就是這個塗鴉小工具的完整思路。繪圖相關的細節還有很多值得深挖,若你有更好的實作方式,也歡迎提出來一起討論。

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