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

Android 自定義控件教程(二):手把手實現簡單寫字板

編輯:關於 Android 開發

概述

上一篇文章我們對自定義控件做了一個大體的知識介紹,今天就用所學知識來實現一個簡單的寫字板控件。

先看效果圖:

它的原理很簡單:根據手指寫下的軌跡,實時畫出對應的內容。

實現步驟

Android 官方給出的自定義控件通常需要考慮幾個步驟,下面就按照這個思路來完成今天的寫字板。

1、創建 View 並聲明自定義屬性

創建 View 這一步要考慮的是自定義屬性的聲明與使用。寫字板需要哪些自定義屬性呢?其實就三樣:寫字板的背景顏色、筆的顏色、筆的粗細。首先在 attrs.xml 中聲明:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="WritingBoardView">
        <attr name="boardBackground" format="color"></attr><!--畫板顏色-->
        <attr name="paintColor" format="color"></attr><!--畫筆顏色-->
        <attr name="paintWidth" format="dimension"></attr><!--畫筆寬度-->
    </declare-styleable>
</resources>

定義屬性就是為了使用,在布局文件中引用:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" xmlns:custom="https://schemas.android.com/apk/res-auto" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.qiangyu.test.writingboardview.MainActivity">
    <com.qiangyu.test.writingboardview.view.WritingBoardView android:layout_width="match_parent" android:layout_height="match_parent" custom:paintColor="@color/colorAccent" custom:boardBackground="@color/colorPrimary" custom:paintWidth="3dp"/>
</RelativeLayout>

這樣就簡單地設置了 boardBackground、paintWidth 和 paintColor 三個屬性。使用時只需注意命名空間:系統提供的屬性用 android,自定義屬性則自行聲明命名空間,寫法為 xmlns:你取的名="https://schemas.android.com/apk/res-auto",其中 res-auto 也可以換成你控件的包名。

要在代碼中獲取到布局文件裡設置的屬性,必須實現帶有 Context、AttributeSet 參數的構造方法:

private int mBoardBackground;   // 畫板顏色
private int mPaintColor;        // 畫筆顏色
private int mPaintWidth;        // 畫筆寬度
private Path mPath;
private Paint mPaint;           // 畫筆
public WritingBoardView(Context context) {
    this(context, null);
}
public WritingBoardView(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
}
public WritingBoardView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.WritingBoardView);
    mBoardBackground = a.getColor(R.styleable.WritingBoardView_boardBackground, Color.WHITE);
    mPaintColor = a.getColor(R.styleable.WritingBoardView_paintColor, Color.BLUE);
    mPaintWidth = a.getDimensionPixelSize(R.styleable.WritingBoardView_paintWidth, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 5, getResources().getDisplayMetrics()));
    a.recycle();
    mPaint = new Paint();
    mPath = new Path();
    setBackgroundColor(mBoardBackground);
    mPaint.setColor(mPaintColor);
    mPaint.setStrokeWidth(mPaintWidth);
    mPaint.setStyle(Paint.Style.STROKE);
    mPaint.setAntiAlias(true);
}

以上代碼確保每個構造方法最終都會調用第三個構造方法裡的 init(context, attrs),用來獲取自定義屬性並初始化相關信息。通過這種固定寫法,我們簡單地拿到了自定義屬性,並為當前 View 設置了背景、為 Paint 設置了樣式和顏色。而完成寫字板最關鍵的,正是這裡的 Path 類。

認識 Path 類

先看它的構造方法注釋:

/**
 * The Path class encapsulates compound (multiple contour) geometric paths
 * consisting of straight line segments, quadratic curves, and cubic curves.
 * It can be drawn with canvas.drawPath(path, paint), either filled or stroked
 * (based on the paint's Style), or it can be used for clipping or to draw
 * text on a path.
 */
public class Path {
    ...
}

大致意思是:Path 封裝了由直線段、二次曲線、三次曲線等組成的複合幾何路徑。我們可以通過 canvas.drawPath(path, paint) 把它畫出來。最終的繪制正是要用到 drawPath。

Path 中包含很多設置幾何圖形的方法,如 addRect、addArc 等。今天重點用到兩個方法:

/**
 * Set the beginning of the next contour to the point (x,y).
 */
public void moveTo(float x, float y) {
    native_moveTo(mNativePath, x, y);
}

moveTo 方法用來設置下一段連線或圖形的起始位置。

/**
 * Add a line from the last point to the specified point (x,y).
 */
public void lineTo(float x, float y) {
    isSimplePath = false;
    native_lineTo(mNativePath, x, y);
}

lineTo 方法則簡單地添加一條從上一個點到當前點的直線。有了這兩個方法,我們就能實現寫字板了。

2、處理 View 的布局

由於這個自定義控件本身就需要佔用一整塊區域作為寫字板,所以不用做特別的布局處理,只是在 MeasureSpec 的 mode 為 UNSPECIFIED 時可能會導致布局顯示不出來。這裡就不做特殊處理了。

3、繪制 View 並與用戶交互

由於該控件本身就需要交互才能產生效果,所以這一步與前面的初始化放在一起考慮。前面說到 Canvas 有一個 drawPath 方法,它最終畫出什麼樣子,取決於 Path 裡包含的信息。

要實現實時顯示手寫內容,只需在手指滑動時獲取坐標,通過 Path 的 lineTo 方法把線一點一點連起來;而當手指抬起再落下時應該又是一條新的線,所以在 ACTION_DOWN 時需要調用 moveTo 為下一條軌跡設置起點:

@Override
public boolean onTouchEvent(MotionEvent event) {
    float touchX = event.getX();
    float touchY = event.getY();
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            mPath.moveTo(touchX, touchY);   // 重新設置即將出現的線的起點
            break;
        case MotionEvent.ACTION_MOVE:
            mPath.lineTo(touchX, touchY);   // 連線
            break;
        case MotionEvent.ACTION_UP:
            break;
    }
    invalidate();   // 通知系統重繪
    return true;    // 要處理當前事件
}

在 onTouch 中 return true 表示要處理當前事件,並且在每次操作後調用 invalidate 觸發重繪。此時我們的 onDraw 方法只需簡單地調用 drawPath 即可:

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.drawPath(mPath, mPaint);
}

總結

歸根結底,就是通過手指的觸摸事件來控制軌跡的改變,按照固定的自定義控件模式,一個簡單的寫字板就大功告成了!感興趣的話還可以進一步擴展,比如加入運行時動態改變畫筆顏色、畫板顏色,或者增加橡皮擦功能。

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