編輯:關於 Android 程式設計
這次要做的控件很單純:跟著手指移動的軌跡把筆跡畫出來,就是一個手寫板。

Android 官方文件提到,自定義 View 大致要考慮:創建 View、處理 View 的版面配置、繪製 View、與使用者互動,以及優化已定義的 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 封裝了由直線段、二次曲線與三次曲線組成的複合幾何路徑,可以透過 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() 則是從上一個點連一條線到目前點。有了這兩個方法,手寫板就成形了。
這個控件本身就是一塊畫布,不太需要額外的量測邏輯。實務上唯一要留意的是 UNSPECIFIED 規格下可能導致版面顯示不出來,本篇先不特別處理。
因為效果必須靠互動產生,所以繪製與事件綁在一起看。做法是在 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 繪製來控制記憶體。
Android 實作朋友圈:列表、拍照、多圖選擇與影片錄製
功能概覽這個範例實作了一個類似微信朋友圈的頁面,包含動態列表、下拉更新、文字或圖片或影片發布、相簿多選、拍照與影片錄製預覽。整體可作為 Android 社群功能入門,也能
OpenCV 常用基本數據結構梳理與示例
Mat 大概是人們對 OpenCV 最熟悉的類型,但工程中真正高頻出現的還有幾個更輕量的結構。這裡把它們集中梳理一遍: Vec、Scalar、Point、Size、Rec
圖文並茂:Android簡單創建Activity全流程
本文以圖文並茂的方式,帶大家走一遍在Android中簡單創建Activity的完整流程,適合剛入門的開發者參考。 1)建立一個Android專案 先填寫專案相關資訊:
Android 框架設計模式(四)—— 適配器模式 Adapter
一、適配器模式介紹 適配器在日常生活裡隨處可見,尤其在電子產品上。手機、電腦、家電都會用到適配器來轉換電壓,以提供合適的電壓與訊號。簡單來說,它就是一個介面轉換器——把