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

Android自定義控件:打造一個簡單的手寫板

編輯:關於 Android 程式設計

這次要做的控件很單純:跟著手指移動的軌跡把筆跡畫出來,就是一個手寫板。

一、官方建議的五個步驟

Android 官方文件提到,自定義 View 大致要考慮:創建 View、處理 View 的版面配置、繪製 View、與使用者互動,以及優化已定義的 View。本篇就照這個順序走一遍。

1. 創建 View:宣告自定義屬性

手寫板需要哪些可調參數?其實就三個:畫板底色、筆的顏色、筆的粗細。先在 attrs 中宣告:

 <?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> 

命名空間的寫法是 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() 取得自定義屬性並完成初始化:設定畫板背景、Paint 的顏色與筆寬,並開啟抗鋸齒。用過的 TypedArray 記得 recycle()。

認識 Path

官方對 Path 的註解大意是:Path 封裝了由直線段、二次曲線與三次曲線組成的複合幾何路徑,可以透過 canvas.drawPath(path, paint) 描邊或填滿繪製。我們最終要用的正是 drawPath。

Path 提供了 addRect、addArc 等各種幾何方法,本篇只需要其中兩個:

 /** * Set the beginning of the next contour to the point (x,y). * * @param x The x-coordinate of the start of a new contour * @param y The y-coordinate of the start of a new contour */ 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). * If no moveTo() call has been made for this contour, the first point is * automatically set to (0,0). * * @param x The x-coordinate of the end of a line * @param y The y-coordinate of the end of a line */ public void lineTo(float x, float y) { isSimplePath = false; native_lineTo(mNativePath, x, y); } 

lineTo() 則是從上一個點連一條線到目前點。有了這兩個方法,手寫板就成形了。

2. 處理 View 的版面配置

這個控件本身就是一塊畫布,不太需要額外的量測邏輯。實務上唯一要留意的是 UNSPECIFIED 規格下可能導致版面顯示不出來,本篇先不特別處理。

3. 繪製 View 與使用者互動

因為效果必須靠互動產生,所以繪製與事件綁在一起看。做法是在 ACTION_MOVE 時把座標用 lineTo 串進 Path,手指抬起再落下則代表新的一筆,因此在 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;//要處理當前事件 } 

onTouchEvent 回傳 true 代表我們要攔下這個事件;每次操作後呼叫 invalidate() 請系統重繪,而 onDraw 就變得非常單純:

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

總結

整體邏輯就是:用觸摸事件餵座標給 Path,再由 drawPath 一次畫出來。照著官方那套固定模式走,一個簡單的自定義控件就完成了。

想再往前一步的話,可以加上執行期動態換筆色、換畫板底色,甚至補上橡皮擦功能(用 PorterDuff 模式或改畫板色覆蓋);若筆跡很長,記得考慮改用 Bitmap layered 繪製來控制記憶體。

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