編輯:關於 Android 開發
上一篇文章我們對自定義控件做了一個大體的知識介紹,今天就用所學知識來實現一個簡單的寫字板控件。
先看效果圖:
它的原理很簡單:根據手指寫下的軌跡,實時畫出對應的內容。
Android 官方給出的自定義控件通常需要考慮幾個步驟,下面就按照這個思路來完成今天的寫字板。
創建 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 類。
先看它的構造方法注釋:
/**
* 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 方法則簡單地添加一條從上一個點到當前點的直線。有了這兩個方法,我們就能實現寫字板了。
由於這個自定義控件本身就需要佔用一整塊區域作為寫字板,所以不用做特別的布局處理,只是在 MeasureSpec 的 mode 為 UNSPECIFIED 時可能會導致布局顯示不出來。這裡就不做特殊處理了。
由於該控件本身就需要交互才能產生效果,所以這一步與前面的初始化放在一起考慮。前面說到 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);
}
歸根結底,就是通過手指的觸摸事件來控制軌跡的改變,按照固定的自定義控件模式,一個簡單的寫字板就大功告成了!感興趣的話還可以進一步擴展,比如加入運行時動態改變畫筆顏色、畫板顏色,或者增加橡皮擦功能。
Android 開發環境搭建與第一個程式實作:Eclipse + ADT 完整流程
Android 開發環境搭建與第一個程式實作:Eclipse + ADT 完整流程 一、環境搭建 所需材料:Eclipse、ADT、SDK、JDK。 請先準備好 ADT-
從網頁點擊開啟 App:Custom Scheme URI 與 Intent Scheme 用法及安全風險
一、網頁開啟 App 是怎麼回事 Android 支援一個很方便的特性:使用者點擊網頁中的連結就能開啟 App,或在某個 App 內點連結開啟另一個 App(App Li
Linux 死鎖排查實戰:用 pstack 與 gdb 精準定位交叉持鎖
死鎖(deadlock)指的是兩個或多個線程在執行過程中互相爭奪資源而形成的循環等待:沒有外力介入,誰都推不進去。最典型的就是交叉持鎖——線程 1 鎖住 A 等 B,線程
手機影音實戰(五):播放器狀態欄、列表傳遞與手勢控制
手機影音實戰(五):讓播放器變得完整 這一階段要補上幾個決定用戶觀感的細節:狀態欄的電量與時間顯示、視頻列表的跨頁面傳遞、播放完成後的自動續播,以及手勢驅動的控制面板。