編輯:關於 Android 開發
這篇拖了很久的文章,算是對自己年初一個承諾的交代。當時有朋友希望整理一份 Android Canvas 相關的總結,結果一放就放到忘了;最近社群裡不斷有人催更,於是就有了這一篇堪稱「超級基礎」的文章——之所以說基礎,是因為這類內容寫法相對固定,把 API 用熟即可。

談自定義繪製,第一個要認識的就是 Canvas(android.graphics.Canvas)。它的實質就是一塊畫布:我們既能設定畫布的屬性,也能在上面畫任何想畫的東西。還記得自定義 View 時一定會覆寫的那個方法嗎?
protected void onDraw(Canvas canvas) { }
它的形參 Canvas 就是關鍵。我們把內容畫到這個畫布上,之後交給系統框架顯示。整個 View 樹的繪圖流程由 ViewRootImpl 的 performTraversals() 觸發,該方法依先前記錄的狀態判斷是否需要重新測量(measure)、重新定位(layout)、重新繪製(draw)。ViewRootImpl 內部持有一個 Surface 成員,重繪時會把該 Surface 的 Canvas 透過 draw 方法遞迴往下傳,從 ViewGroup 一路派發到最末端的 View 的 onDraw(Canvas canvas)。
這就解釋了 onDraw 那個形參的由來。當我們把自定義邏輯畫上去之後,系統框架會透過 SurfaceFlinger 服務把測量、配置、繪製後的 Surface 渲染到螢幕上。這個過程相當複雜,此處不展開,重點是理解「Canvas 從哪裡來」。
換句話說,Android 上所有 View 元件,本質上都是用這套 Paint + Canvas + Path 的組合堆出來的。把基礎搞懂,剩下的都是萬變不離其宗。
提示:本文篇幅很長,建議分小節閱讀。之所以不拆成多篇,是因為單篇管理方便,複習時直接搜尋關鍵字即可。
有了畫布,還需要一支筆,也就是 Paint。它繼承自 Object,屬於 graphics 家族,有一個子類 TextPaint。舉例來說,繪製文本需要換行時,就應該用 StaticLayout 搭配 TextPaint,而不是硬用 Paint 去手算一堆座標。
Paint 的方法大致可分成兩類:一類處理文字相關設定,一類處理圖形繪製相關設定。就像拿到一張白紙,調色與選筆的過程就是 Paint 的使用過程。
行距與字距
float getFontSpacing():取得字元行間距。getLetterSpacing() / setLetterSpacing(float):取得與設定字元間距。裝飾線
isUnderlineText() / setUnderlineText(boolean):是否有、以及是否加上底線。isStrikeThruText() / setStrikeThruText(boolean):刪除線。大小與字型
getTextSize() / setTextSize(float):注意 Paint.setTextSize 傳入的單位是 px,而 TextView.setTextSize 傳入的是 sp,跨解析度時要特別小心。getTypeface() / setTypeface(Typeface):Android 預設有四種樣式:BOLD(粗體)、BOLD_ITALIC(粗體傾斜)、ITALIC(傾斜)、NORMAL(正常),也可以透過 Typeface 載入自訂字型。hasGlyph(String):判斷目前 Typeface 是否支援該字串。傾斜與縮放
getTextSkewX() / setTextSkewX(float):官方推薦值 -0.25,負值右傾、正值左傾,預設 0。getTextScaleX() / setTextScaleX(float):沿 X 軸水平縮放,預設 1。大於 1 放大、小於 1 縮小,會同時改變寬度並拉伸或壓縮字元。對齊
getTextAlign() / setTextAlign(Paint.Align):可取值 CENTER、LEFT、RIGHT。斷行計算
breakText(...) 系列:計算在指定寬度下能顯示多少字元,同時可回傳實際佔用的長度。private static final String STR = "我們XXOOCC";
mPaint.setTextSize(50);
float[] value = new float[1];
int ret = mPaint.breakText(STR, true, 200, value);
Log.i("YYYY", "breakText=" + ret + ", STR=" + STR.length() + ", value=" + value[1]);
// breakText=5, STR=8, value=195.0
字型度量(很重要)
getFontMetrics():回傳 FontMetrics 物件。getFontMetrics(Paint.FontMetrics metrics):回傳行間距,metrics 不為空時會一併帶回數值。getFontMetricsInt() / getFontMetricsInt(Paint.FontMetricsInt fmi):同上,只是回傳 int。FontMetrics 與 FontMetricsInt 都有 top、ascent、descent、bottom、leading 這幾個屬性:

可以注意到,canvas.drawText 傳入的 y 其實是圖中的 base 基線,文字座標以基線為參考。各屬性含義:
top:基線到最高字元的最大值(即 ascent 的最大值)ascent:基線到最高字元的推薦值descent:基線到最低字元的推薦值bottom:基線到最低字元的最大值(即 descent 的最大值)leading:行之間推薦的額外高度,單行文字一般為 0因此,取得文字高度的方式是 mPaint.ascent() + mPaint.descent()(實務上取絕對值),取得文字寬度則是 mPaint.measureText(text)。
邊界與寬度
getTextBounds(...):取得文字寬高,透過 Rect 拿到整數值。measureText(...) 系列:粗略取得文字寬度,回傳浮點數。getTextWidths(...) 系列:精確計算每個字元的寬度。區域與顯示效果
getTextLocale() / setTextLocale(Locale):設定文字區域(中文、法文等),一般傳 Locale.getDefault() 即可。isSubpixelText() / setSubpixelText(boolean):設為 true 有助於文字在 LCD 螢幕上的顯示品質。isFakeBoldText() / setFakeBoldText(boolean):是否使用仿粗體,小字級時效果較差。isLinearText() / setLinearText(boolean):是否開啟線性文字。預設 Android 會用一張 Bitmap 作為單一字元快取,會佔用空間;設為 true 可省下這塊空間。文字轉路徑
getTextPath(...):取得文字輪廓的 Path。Path path = new Path(); mPaint.getTextPath(STR, 0, STR.length(), 0, 800, path); path.close(); mPaint.setColor(Color.RED); mPaint.setStrokeWidth(5); canvas.drawPath(path, mPaint); // 特別注意:Path 一定要 close,否則無效。
reset():清空畫筆、復位。set(Paint src):套用外來的 Paint 設定。getFlags() / setFlags(int):抗鋸齒、防抖等旗標,可取值 ANTI_ALIAS_FLAG、DITHER_FLAG、FILTER_BITMAP_FLAG、LINEAR_TEXT_FLAG、SUBPIXEL_TEXT_FLAG、UNDERLINE_TEXT_FLAG、STRIKE_THRU_TEXT_FLAG 等,多個設定可用按位或合併。setARGB(int a, int r, int g, int b)、getAlpha() / setAlpha(int)、getColor() / setColor(int):顏色相關。isAntiAlias() / setAntiAlias(boolean):是否啟用抗鋸齒,會消耗較多資源、繪製變慢,但一般建議開啟。isDither() / setDither(boolean):圖像抖動處理,可讓漸層色彩更平滑飽滿。isFilterBitmap() / setFilterBitmap(boolean):圖像過濾,一般設為 true。線端樣式
getStrokeCap() / setStrokeCap(Paint.Cap):當樣式為 STROKE 或 FILL_OR_STROKE 時,線段起訖點的樣式,預設 BUTT。
轉角樣式
getStrokeJoin() / setStrokeJoin(Paint.Join):線段連接處的輪廓樣式,預設 MITER。
getStrokeMiter() / setStrokeMiter(float):傾斜度。getStyle() / setStyle(Paint.Style):FILL(實心)、STROKE(空心)、FILL_AND_STROKE(同時)。注意 STROKE 與 FILL_AND_STROKE 模式下外輪廓會向外擴張。getStrokeWidth() / setStrokeWidth(float):線寬,僅在 STROKE 或 FILL_AND_STROKE 時有效。clearShadowLayer() / setShadowLayer(float radius, float dx, float dy, int shadowColor):陰影層,例如畫圓時加上外擴的光暈。getShader() / setShader(Shader) 是 Paint 中最值得花時間研究的方法之一。Shader 的直接子類包含:
Shader 基類有一個 Shader.TileMode 列舉:CLAMP 是拉伸最後一個像素鋪滿、REPEAT 類似電腦桌布橫縱向重複、MIRROR 則是不足處不斷翻轉鏡像平鋪。此外還提供 getLocalMatrix(Matrix) 與 setLocalMatrix(Matrix) 兩個矩陣變換方法。
BitmapShader 實例(右側是經過圓角渲染處理後的結果):

/**
* 把 bitmap 渲染成圓角圖片
* new BitmapShader(bitmap, tileX, tileY)
* tileX、tileY 是位圖在 XY 方向的 TileMode 模式
*/
Paint mPaint = new Paint();
BitmapDrawable drawable = (BitmapDrawable) getResources().getDrawable(R.drawable.icon1);
Bitmap bitmap = drawable.getBitmap();
BitmapShader shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
/* 以下四行 Matrix 可不設定,這裡是為了處理不等寬高圖片渲染後鋪不滿的問題
Matrix matrix = new Matrix();
float scale = Math.max(bitmap.getWidth(), bitmap.getHeight()) * 1.0f
/ Math.min(bitmap.getWidth(), bitmap.getHeight());
matrix.setScale(scale, scale);
shader.setLocalMatrix(matrix);
*/
mPaint.setShader(shader);
canvas.drawCircle(bitmap.getWidth() / 2, bitmap.getHeight() / 2, bitmap.getHeight() / 2, mPaint);
/* 也可以這樣實現
ShapeDrawable shapeDrawable = new ShapeDrawable(new OvalShape());
shapeDrawable.getPaint().setShader(shader);
shapeDrawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getWidth());
shapeDrawable.draw(canvas);
*/
LinearGradient 線性渲染:文字漸變、色度條多半靠它完成。最多參數的建構子如下:
/**
* x0、y0 漸變起始點座標;x1、y1 漸變結束點座標
* colors 顏色的 int 陣列
* positions 相對位置的顏色陣列,null 則顏色沿漸變線均勻分布
* tile 渲染器平鋪模式 Shader.TileMode
*/
public LinearGradient(float x0, float y0, float x1, float y1,
int[] colors, float[] positions, Shader.TileMode tile)
RadialGradient 環形渲染:搭配 Paint 的 alpha 值可以畫出水波紋之類的效果。
/**
* x、y 圓心座標;radius 圓半徑
* colors 渲染顏色陣列;positions 相對位置陣列,可為 null
* tile 渲染器平鋪模式
*/
public RadialGradient(float x, float y, float radius,
int[] colors, float[] positions, Shader.TileMode tile)
SweepGradient 掃描漸變:微信雷達加好友的掃描動畫、各種手機加速大師的掃描介面,都是這東西。
/** * cx、cy 渲染中心座標 * color0 起始渲染顏色;color1 結束渲染顏色 */ public SweepGradient(float cx, float cy, int color0, int color1) /** * colors 圍繞中心渲染的顏色陣列,最少要有兩種顏色,切記! * positions 相對位置陣列,為 null 則均勻分布 */ public SweepGradient(float cx, float cy, int[] colors, float[] positions)
ComposeShader 組合渲染:類似動畫中的組合動畫,可以整合上面幾種渲染器。
/** * shaderA、shaderB 為兩個渲染器 * mode 為組合模式,可使用 Xfermode 或 PorterDuff.Mode 物件 */ public ComposeShader(Shader shaderA, Shader shaderB, Xfermode mode) public ComposeShader(Shader shaderA, Shader shaderB, PorterDuff.Mode mode)
getXfermode() / setXfermode(Xfermode) 用來設定兩次繪製相交時的規則。正常情況下,新畫上去的圖會完全遮蓋底下已有的圖;這個方法就是拿來改變這條規則的,傳入 null 可清除先前的設定。
// canvas 上原有的圖片稱為 dst // 新畫上去的圖片稱為 src Canvas canvas = new Canvas(dstBitmap); paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); canvas.drawBitmap(srcBitmap, 0f, 0f, paint);
Xfermode 有三個子類,其中兩個已被標記為 Deprecated,重點放在第三個:

AvoidXfermode(已棄用):指定一個顏色與容差值,控制 Paint 是否在該容差顏色範圍內繪製或不繪製。
/** * opColor 要匹配的目標顏色 * tolerance 容差值,0 代表最小容差(像素值需與 opColor 完全相同),255 代表最大容差 * mode 有兩個可取列舉值: * Avoid 模式:只在目標像素值與 opColor 匹配成功處繪製 * Target 模式:只在匹配不成功處繪製 */ public AvoidXfermode(int opColor, int tolerance, Mode mode)
// !!! 由於高版本 API 已 Deprecated,必須關閉 View 硬體加速才有效果 !!! // 例子:把紅色五角星轉為黑色,同時保持背景色不變 // 可由此延伸出依手勢觸發漸變的效果,例如微信底部 Tab 圖示在滑動切換頁面時的漸變 mBitmap = ((BitmapDrawable) getResources().getDrawable(R.drawable.red_star)).getBitmap(); mAvoidPaint = new Paint(); mAvoidPaint.setColor(Color.BLACK); // 準備把接近紅色的像素替換掉 mAvoidXfermode = new AvoidXfermode(Color.RED, 10, Mode.TARGET); canvas.drawBitmap(mBitmap, mLeft, mTop, mAvoidPaint); mAvoidPaint.setXfermode(mAvoidXfermode); canvas.drawRect(mAvoidDestRect, mAvoidPaint); // 此時畫布上的五角星就變成黑色了
PixelXorXfermode(已棄用):覆蓋已有像素時進行互斥或運算。
PixelXorXfermode(int opColor)
核心就是 opPixColor ^ srcPixColor ^ dstPixColor,屬於過時做法。
PorterDuffXfermode(重點):非常強大的轉換模式,透過 PorterDuff 規則控制 Paint 如何與既有 Canvas 內容做圖層疊加。

PorterDuff.Mode 提供了十六種枚舉值。其中 Sa 是來源 alpha、Da 是目標 alpha、Sc 是來源色值、Dc 是目標色值,透過像素運算得出各種效果。特別注意:這些模式不僅用於圖形疊加裁剪,也應用於圖像色彩混合,後面的 ColorFilter 會再提到。
掌握了它, circular 水波紋上升進度條、文字進度條、橡皮擦、刮刮樂這類效果都能做出來。
getMaskFilter() / setMaskFilter(MaskFilter) 針對 Alpha 通道做濾鏡處理(ColorFilter 則是針對 RGB)。MaskFilter 本身沒有實作方法,實務上用它的兩個子類:BlurMaskFilter(模糊遮罩)與 EmbossMaskFilter(浮雕遮罩)。
// radius 陰影範圍;style 模糊類型 BlurMaskFilter(float radius, Blur style)
// 必須關閉硬體加速才有效果 setLayerType(View.LAYER_TYPE_SOFTWARE, null); Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); paint.setColor(Color.RED); // 具備 alpha 通道的顏色 paint.setMaskFilter(new BlurMaskFilter(20, BlurMaskFilter.Blur.NORMAL)); canvas.drawRect(rect, paint);

// 提取 Bitmap 的 Alpha 通道後再模糊 Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher); Bitmap bitmapAlpha = bitmap.extractAlpha(); paint.setColor(Color.RED); paint.setMaskFilter(new BlurMaskFilter(30, BlurMaskFilter.Blur.SOLID)); canvas.drawBitmap(bitmapAlpha, 300, 500, paint); // 模糊陰影 canvas.drawBitmap(bitmap, 300, 500, paint); // 原圖

Blur 列舉共四個值:

EmbossMaskFilter:做出凸起立體的浮雕效果,同樣需要關閉硬體加速。
/** * direction 長度為 3 的陣列 [x, y, z],指定光源方向 * ambient 環境光,取值 0 到 1 * specular 鏡面反射係數 * blurRadius 模糊半徑 */ public EmbossMaskFilter(float[] direction, float ambient, float specular, float blurRadius)
paint.setMaskFilter(new EmbossMaskFilter(new float[]{20, 20, 20}, 0.4f, 10, 15));
canvas.drawRect(rect5, paint);

getPathEffect() / setPathEffect(PathEffect) 用來設定線條樣式,效果來自 PathEffect 的六個子類:

Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(10);
PathEffect[] pathEffects = new PathEffect[7];
// 不設定效果,預設轉角處帶有尖角
pathEffects[0] = null;
// 用平滑圓角代替尖角,radius 為轉角圓滑程度
pathEffects[1] = new CornerPathEffect(100);
// 虛線輪廓
// intervals 第一個參數為實線長度,第二個為虛線長度,以此類推
// phase 偏移值,動態改變可產生動畫效果
pathEffects[2] = new DashPathEffect(new float[]{50, 20, 5, 10}, 0);
// 加入隨機性,類似生鏽鐵絲
// segmentLength 雜點密度,值越小越密集
// deviation 雜點突出大小
pathEffects[3] = new DiscretePathEffect(5f, 5f);
// 自訂虛線樣式
// shape 自訂路徑樣式;advance 每個 shape 間距;phase 偏移值
// style: ROTATE 旋轉連接 / MORPH 伸縮形變連接 / TRANSLATE 平行平移連接
Path pathShape = new Path();
pathShape.addRect(0, 0, 10, 10, Path.Direction.CCW);
pathEffects[4] = new PathDashPathEffect(pathShape, 20, 0, PathDashPathEffect.Style.ROTATE);
// 組合兩種效果:先套用 innerpe,再複合 outerpe
pathEffects[5] = new ComposePathEffect(pathEffects[3], pathEffects[4]);
// 組合兩種效果:把兩種效果相加後作用於路徑
pathEffects[6] = new SumPathEffect(pathEffects[2], pathEffects[4]);
Path path = new Path();
path.moveTo(0, 0);
for (int index = 1; index < 20; index++) {
path.lineTo(index * 40, (float) Math.random() * 150);
}

MaskFilter 過濾 Alpha,ColorFilter 則過濾 RGB(A)。各種美圖 App 的核心功力都在這裡。

ColorMatrixColorFilter:透過顏色矩陣改變像素色值。每個像素以 RGBA 形式載入記憶體,因此改色需要 ColorMatrix 支援。顏色矩陣本質上是一個 5×4 矩陣(每行對應 RGBA 其中一項):

而每個像素的呈現效果取決於一個 5×1 的分量矩陣:

兩者相乘後的結果就是:
R' = a*R + b*G + c*B + d*A + e; G' = f*R + g*G + h*B + i*A + j; B' = k*R + l*G + m*B + n*A + o; A' = p*R + q*G + r*B + s*A + t;
本質就是線性代數。實務上只要調整 ColorMatrix 的參數,就能得到各種濾鏡效果:
// 傳入 ColorMatrix 矩陣 public ColorMatrixColorFilter(ColorMatrix matrix) // 傳入自訂矩陣(一維陣列) public ColorMatrixColorFilter(float[] array)
public void setImageArgb(float alpha, float red, float green, float blue) {
mColorMatrix = new ColorMatrix(new float[] {
red, 0, 0, 0, 0,
0, green, 0, 0, 0,
0, 0, blue, 0, 0,
0, 0, 0, alpha, 0,
});
mPaint.setColorFilter(new ColorMatrixColorFilter(mColorMatrix));
postInvalidate();
}
傳入不同參數即可得到各種效果,例如老照片風格、線上/離線頭像的灰階切換。
LightingColorFilter:曝光顏色過濾。
/** * mul (colorMultiply) 色彩倍增,16 進位 0xAARRGGBB * add (colorAdd) 色彩添加,16 進位 0xAARRGGBB */ public LightingColorFilter(int mul, int add)
// 過濾掉紅色、加強綠色 mPaint.setColorFilter(new LightingColorFilter(0xFF00FFFF, 0x0000FF00));
計算方式為 (mul * 原色值 + add) % 255。特別注意:它不處理 Alpha,只對 RGB 有效。
PorterDuffColorFilter:圖層混合顏色過濾。
// color 16 進位顏色值 // mode PorterDuff.Mode 混合模式 public PorterDuffColorFilter(int color, PorterDuff.Mode mode)
也就是把畫布上的像素與我們設定的 color 以 mode 方式疊加。這裡的 mode 與前面 Xfermode 提到的 PorterDuff.Mode 是同一套規則,只是套用場景不同。
Canvas() / Canvas(Bitmap bitmap):建構子。自定義 View 通常由上層傳入;單獨 new 出來的常與 setBitmap() 搭配。注意:參數 Bitmap 必須是 mutable 可變的。setBitmap(Bitmap bitmap):設定可變位圖。getDensity() / setDensity(int):畫布密度,預設為 Bitmap 密度或 DENSITY_NONE。getHeight() / getWidth():畫布高與寬。isHardwareAccelerated():是否已開啟硬體加速。isOpaque():是否支援透明度。getDrawFilter() / setDrawFilter(DrawFilter):DrawFilter 預設無實作,其子類 PaintFlagsDrawFilter 可一次設定多個 Paint 旗標。// clearBits 清除 Paint 已存在的指定 flag;setBits 設定 Paint 的 flag public PaintFlagsDrawFilter(int clearBits, int setBits)
// 抗鋸齒寫法一
paint.setAntiAlias(true);
// 抗鋸齒寫法二,按位操作
canvas.setDrawFilter(new PaintFlagsDrawFilter(0,
Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG));
畫線
/**
* startX、startY 開始點;stopX、stopY 結束點,兩點連成一條線
*/
drawLine(float startX, float startY, float stopX, float stopY, Paint paint)
/**
* pts 點集合
* offset 跳過前面多少個數值
* count 從 offset 開始的點數,必須大於 2
* 預設每兩個點形成一條直線,例如 pts={0,0,100,100,200,200,400,400} 是兩段不連線的線段
*/
drawLines(float[] pts, Paint paint)
drawLines(float[] pts, int offset, int count, Paint paint)
畫點
drawPoint(float x, float y, Paint paint) drawPoints(float[] pts, int offset, int count, Paint paint) drawPoints(float[] pts, Paint paint)
畫矩形
// 傳入左上角與右下角座標 drawRect(float left, float top, float right, float bottom, Paint paint) // 透過 RectF 或 Rect 物件 drawRect(RectF rect, Paint paint) drawRect(Rect r, Paint paint)
RectF 與 Rect 差別不大,只是精度不同。
畫圓角矩形
/** * rx 生成圓角的橢圓 X 軸半徑;ry 為 Y 軸半徑 */ drawRoundRect(float left, float top, float right, float bottom, float rx, float ry, Paint paint) drawRoundRect(RectF rect, float rx, float ry, Paint paint)
畫圓
// cx、cy 圓心座標;radius 半徑 drawCircle(float cx, float cy, float radius, Paint paint)
畫橢圓
drawOval(float left, float top, float right, float bottom, Paint paint) drawOval(RectF oval, Paint paint)
畫弧
/**
* startAngle 起始角度,X 軸正方向為 0 度
* sweepAngle 弧經歷角度
* useCenter 是否連到圓心形成扇形,true 有兩邊,false 只有弧線
*/
drawArc(RectF oval, float startAngle, float sweepAngle, boolean useCenter, Paint paint)
drawArc(float left, float top, float right, float bottom,
float startAngle, float sweepAngle, boolean useCenter, Paint paint)
畫路徑
drawPath(Path path, Paint paint)
畫文字
drawText(String text, float x, float y, Paint paint) drawText(CharSequence text, int start, int end, float x, float y, Paint paint) drawText(char[] text, int index, int count, float x, float y, Paint paint) drawText(String text, int start, int end, float x, float y, Paint paint)
再次提醒:y 參數是基線位置,不是文字頂端。
沿路徑畫文字
drawTextOnPath(String text, Path path, float hOffset, float vOffset, Paint paint) drawTextOnPath(char[] text, int index, int count, Path path, float hOffset, float vOffset, Paint paint) // hOffset 與路徑起始點的水平偏移距離 // vOffset 與路徑中心的垂直偏移量,例如把文字從圓內偏移到圓外輪廓
逐字定位畫文字
drawPosText(String text, float[] pos, Paint paint) drawPosText(char[] text, int index, int count, float[] pos, Paint paint) // pos 每兩個數字一組,確定一個文字的座標點
填色
drawRGB(int r, int g, int b) drawARGB(int a, int r, int g, int b) drawColor(int color) drawColor(int color, PorterDuff.Mode mode) // 預設 SRC_OVER
畫圖片
drawBitmap(Bitmap bitmap, float left, float top, Paint paint) drawBitmap(Bitmap bitmap, Rect src, RectF dst, Paint paint) drawBitmap(Bitmap bitmap, Rect src, Rect dst, Paint paint) drawBitmap(Bitmap bitmap, Matrix matrix, Paint paint) /** * src 指定裁剪區域,null 則不裁剪 * dst 裁剪後在 canvas 中顯示的區域,src 會伸縮以適配 dst */
這裡的 Matrix 用來處理圖像的形狀變換:
setTranslate(float dx, float dy) // 平移 setRotate(float degrees, float px, float py) // 旋轉,px/py 為軸心 setScale(float sx, float sy, float px, float py) // 縮放 setSkew(float kx, float ky) // 傾斜
畫扭曲位圖
/**
* meshWidth 橫向劃分格數;meshHeight 縱向劃分格數
* verts 長度為 (meshWidth+1) * (meshHeight+1) * 2 + vertOffset,
* 記錄扭曲後各頂點位置,每兩個數值表示一個座標
* colors 作用於頂點的顏色陣列,一般為 null
*/
drawBitmapMesh(Bitmap bitmap, int meshWidth, int meshHeight, float[] verts,
int vertOffset, int[] colors, int colorOffset, Paint paint)
拉窗簾、視窗關閉時的吸入效果都靠它,原理是按網格重新拉伸圖像。另外 drawVertices() 是它的通用版本,依賴 Canvas.VertexMode 設定。這兩者都不算高頻,基礎範例可參考官方 APIDemo。
DrawPicture 高效繪製
drawPicture(Picture picture) drawPicture(Picture picture, RectF dst) drawPicture(Picture picture, Rect dst)
Picture 位於 android.graphics,相比 Drawable 與 Bitmap 小巧很多,因為它存的是繪製過程而非實際像素。特別注意:開啟硬體加速後失效。
// 開始記錄繪製過程 Canvas beginRecording(int width, int height) static Picture createFromStream(InputStream stream) void draw(Canvas canvas) void endRecording() int getHeight() int getWidth() void writeToStream(OutputStream stream)
對應的 PictureDrawable 繼承自 Drawable,同樣在硬體加速下失效:
PictureDrawable(Picture picture) void draw(Canvas canvas) int getOpacity() Picture getPicture() void setAlpha(int alpha)
// 高效繪製自定義 View 的範本 Picture picture = new Picture(); Canvas canvas = picture.beginRecording(300, 500); // 這裡的所有繪製操作都基於 Picture 回傳的 canvas,切記! picture.endRecording(); PictureDrawable pictureDrawable = new PictureDrawable(picture); // viewCanvas 是自定義 View 中 onDraw 的形參,切記! pictureDrawable.draw(viewCanvas);
Picture 記錄的是繪圖操作而非渲染後的像素結果,所以體積遠小於 Bitmap,回放速度也更快。
取得 Bitmap 尺寸上限
getMaximumBitmapHeight() getMaximumBitmapWidth()
這組方法可以幫你避開這類錯誤:
Bitmap too large to be uploaded into a texture (4405x9705, max=4096x4096).
原因是硬體加速下 GPU 對 OpenGL Render 有尺寸限制,不同機型門檻不同,而這個門檻正是透過這兩個方法取得。
特別注意:所有裁剪相關方法一旦呼叫,除了用 save / restore 處理之外是不可逆的。合理使用這些方法可以有效避免 Overdraw 效能問題。
clipPath
clipPath(Path path) clipPath(Path path, Region.Op op) // 開啟硬體加速無效
先來看 Region 類:
// 建構 public Region() public Region(Region region) public Region(Rect r) public Region(int left, int top, int right, int bottom) // set 系列(會沖掉原本的區域範圍) public void setEmpty() public boolean set(Region region) public boolean set(Rect r) public boolean set(int left, int top, int right, int bottom) public boolean setPath(Path path, Region clip) // 與某區域的交集 // 判斷 public native boolean isEmpty() public native boolean isRect() public native boolean isComplex() // 邊界 public Rect getBounds() public boolean getBounds(Rect r) public Path getBoundaryPath() public boolean getBoundaryPath(Path path) // 包含與相交 public native boolean contains(int x, int y) public boolean quickContains(Rect r) public native boolean quickContains(int left, int top, int right, int bottom) public boolean quickReject(Rect r) public native boolean quickReject(int left, int top, int right, int bottom) public native boolean quickReject(Region rgn) // 平移 public void translate(int dx, int dy) public native void translate(int dx, int dy, Region dst) // 組合 public final boolean union(Rect r) public boolean op(Rect r, Op op) public boolean op(int left, int top, int right, int bottom, Op op) public boolean op(Region region, Op op) public boolean op(Rect rect, Region region, Op op)
Region.Op 的六個值(以下用 region1 去和 region2 組合來說明):
Region.Op.DIFFERENCE // region1 與 region2 不同的區域 Region.Op.INTERSECT // 兩者相交的區域 Region.Op.UNION // 兩者合併後的所有區域 Region.Op.XOR // 相交以外的區域 Region.Op.REVERSE_DIFFERENCE // region2 與 region1 不同的區域 Region.Op.REPLACE // region2 的區域
clipRect / clipRegion
clipRect(Rect rect, Region.Op op) clipRect(RectF rect, Region.Op op) clipRect(int left, int top, int right, int bottom) clipRect(float left, float top, float right, float bottom) clipRect(RectF rect) clipRect(Rect rect) clipRect(float left, float top, float right, float bottom, Region.Op op) clipRegion(Region region) clipRegion(Region region, Region.Op op)
兩組方法的差別只在裁剪形狀,注意被裁剪的 canvas 可以透過 save / restore 復原,但不影響已經畫上去的內容。
其他
getClipBounds() getClipBounds(Rect bounds) // 判斷是否沒和指定區域相交,可作為重複繪製的優化判斷 quickReject(float left, float top, float right, float bottom, Canvas.EdgeType type) quickReject(Path path, Canvas.EdgeType type) quickReject(RectF rect, Canvas.EdgeType type) // Canvas.EdgeType 兩個值: Canvas.EdgeType.AA // 考慮抗鋸齒時邊緣處的四捨五入 Canvas.EdgeType.BW // 邊緣處取最接近的黑或白
// dx 水平平移距離,正數向右、負數向左;dy 垂直平移,正數向下 translate(float dx, float dy) // sx、sy 水平與垂直伸縮比例 // px、py 伸縮參考點,無參數版本預設為 Canvas 原點 scale(float sx, float sy) scale(float sx, float sy, float px, float py) // degrees 旋轉度數,正數順時針、負數逆時針 // px、py 旋轉中心,無參數版本預設為 Canvas 原點 rotate(float degrees) rotate(float degrees, float px, float py) // sx、sy 為傾斜角度的 tan 值 skew(float sx, float sy) concat(Matrix matrix) getMatrix(Matrix ctm) getMatrix() setMatrix(Matrix matrix)
要注意:Canvas 上的繪製本質是圖層疊加。平移前後若在相同座標各畫一次,得到的是兩個圖形疊在一起,因為參考原點已經改變。
這部分是 Canvas 的重點,使用率極高,地圖的圖層概念就是這麼來的:

save / restore
save() save(int saveFlags) getSaveCount() restore() restoreToCount(int saveCount)
在做任何不可逆操作(平移、縮放、旋轉、裁剪)之前,都應該先 save(),做完再 restore() 回到原狀態。getSaveCount() 的回傳值可以傳給 restoreToCount(),精準回到某個 save 節點。帶參數的 save 則用來指定 restore 時哪些狀態需要還原。
saveLayer 系列(離屏緩衝)
saveLayer(RectF bounds, Paint paint, int saveFlags) saveLayer(RectF bounds, Paint paint) saveLayer(float left, float top, float right, float bottom, Paint paint) saveLayer(float left, float top, float right, float bottom, Paint paint, int saveFlags) saveLayerAlpha(RectF bounds, int alpha, int saveFlags) saveLayerAlpha(RectF bounds, int alpha) saveLayerAlpha(float left, float top, float right, float bottom, int alpha, int saveFlags) saveLayerAlpha(float left, float top, float right, float bottom, int alpha)
與 save() 類似,但具備離屏緩衝能力:save 之後等同新開一張 offscreen bitmap,在其上繪製的內容要等到 restore 時才會合成回 Canvas。這組方法效能代價較高,使用時要特別小心。
從 Android 3.0 起,我們可以改用 View 的 setLayerType() 來控制:
LAYER_TYPE_NONE // 一般方式繪製,不使用離屏緩衝,預設值 LAYER_TYPE_HARDWARE // 開啟硬體加速時繪製到硬體紋理,否則等同 SOFTWARE LAYER_TYPE_SOFTWARE // 繪製到一張 Bitmap 中
實務建議:當自定義 View 或對既有 View 做動畫、漸變等特效時,建議先透過 setLayerType() 設為 View.LAYER_TYPE_HARDWARE,操作完成後再設回 View.LAYER_TYPE_NONE。這樣可以提升繪製效率、避免重複的無用繪製。
特別是連續變更 alpha、x、y、translationX/Y、scaleX/Y、pivotX/Y、rotation、rotationX/Y 這些屬性時,其實就是在間接操作 layer——這也正是動效看起來卡頓的常見原因。
Path 只能算輔助工具類,封裝的是路徑數值本身。
建構
public Path() public Path(Path src) set(Path src)
基本繪製
moveTo(float x, float y) // 起點 lineTo(float x, float y) // 直線終點,同時也是下一次 lineTo 的起點,可連續呼叫 rMoveTo(float dx, float dy) // 在當前終點基礎上相對移動,得到新起點 rLineTo(float dx, float dy) // 與 lineTo 類似,但以上一個終點為參考,而非 (0,0) close() // 把首尾點連成閉環
加入圖形
addArc(RectF oval, float startAngle, float sweepAngle) addArc(float left, float top, float right, float bottom, float startAngle, float sweepAngle) addCircle(float x, float y, float radius, Path.Direction dir) addOval(RectF oval, Path.Direction dir) addOval(float left, float top, float right, float bottom, Path.Direction dir) addRect(RectF rect, Path.Direction dir) addRect(float left, float top, float right, float bottom, Path.Direction dir) addRoundRect(RectF rect, float rx, float ry, Path.Direction dir) addRoundRect(RectF rect, float[] radii, Path.Direction dir) addRoundRect(float left, float top, float right, float bottom, float rx, float ry, Path.Direction dir) addRoundRect(float left, float top, float right, float bottom, float[] radii, Path.Direction dir) arcTo(RectF oval, float startAngle, float sweepAngle) arcTo(RectF oval, float startAngle, float sweepAngle, boolean forceMoveTo) arcTo(float left, float top, float right, float bottom, float startAngle, float sweepAngle, boolean forceMoveTo) // Path.Direction 兩個值: Path.Direction.CCW // 逆時針方向 Path.Direction.CW // 順時針方向
方向設定主要影響動畫路徑的走向,單純畫線看不出差別。
其他操作
offset(float dx, float dy, Path dst) // 平移 Path 或指定的 dst offset(float dx, float dy) reset() // 清空路徑資訊 rewind() // 清除所有直線曲線,但保留內部資料結構,以便更好地重複使用
填充模式
setFillType(Path.FillType ft) getFillType() FillType.WINDING // 預設值,兩圖形相交則正常相交顯示 FillType.EVEN_ODD // 取 Path 所在且不相交的區域 FillType.INVERSE_WINDING // 取 Path 的外部區域 FillType.INVERSE_EVEN_ODD // 取 Path 外部與相交的區域 isInverseFillType() // 是否為逆填充模式 toggleInverseFillType() // 切換逆狀態
判斷與計算
isEmpty() // 不含任何線條與曲線則回傳 true isRect(RectF rect) // 是否為矩形,若是且 rect 不為 null 則帶回區域 computeBounds(RectF bounds, boolean exact) // 計算所在區域,只有 0 或 1 個點時回傳 (0,0,0,0) incReserve(int extraPtCount) // 提示即將加入更多點,讓 Path 更有效地配置儲存 setLastPoint(float dx, float dy) // 設定最後一個點
合併與變換
addPath(Path src, float dx, float dy) // 平移 dx、dy 後拼接 addPath(Path src) addPath(Path src, Matrix matrix) // 矩陣變換後加入 transform(Matrix matrix, Path dst) // dst 為 null 則存回當前 Path transform(Matrix matrix)
貝茲曲線
二階貝茲曲線,只有一個控制點 (x1, y1),(x2, y2) 是結束點。若沒有先用 moveTo 指定起點,起點預設為 (0, 0)。

mPath.quadTo(100, 500, 300, 800); // 平滑曲線 canvas.drawPath(mPath, mPaint); rQuadTo(float dx1, float dy1, float dx2, float dy2) // 相對座標版本
三階貝茲曲線,兩個控制點 (x1, y1)、(x2, y2),(x3, y3) 是結束點。

mPath.cubicTo(100, 80, 200, 200, 300, 300); // 平滑曲線 canvas.drawPath(mPath, mPaint); rCubicTo(float x1, float y1, float x2, float y2, float x3, float y3) // 相對座標版本
Paint 講完了、Canvas 玩完了、Path 也搞定了,是不是覺得已經揭開了自定義繪製的面紗?其實還遠遠不夠,不過掌握這些應付七成場景綽綽有餘,尤其 Path 能做出很炫的動畫。
為了把 Path 再升級一層,這裡要介紹 PathMeasure。不論多複雜的 Path,在 PathMeasure 眼中就是一條線,因此它能很方便地在路徑上取位置、算座標。
PathMeasure() PathMeasure(Path path, boolean forceClosed) // forceClosed 決定是否 close 這個 path setPath(Path path, boolean forceClosed) getLength() // 測量路徑長度 isClosed() // 輪廓是否為閉環 nextContour() // 移到下一個輪廓,多輪廓 Path 才用得到,有則回傳 true /** * distance 傳入 0 <= distance <= getLength(), * 自動計算該距離處的座標點與切線值,分別存入 pos 與 tan */ getPosTan(float distance, float[] pos, float[] tan) /** * startD、stopD 傳入起訖距離,回傳這段區間的 Path 到 dst * startWithMoveTo 決定起始點是否以 moveTo 座標為參照 */ getSegment(float startD, float stopD, Path dst, boolean startWithMoveTo) getMatrix(float distance, Matrix matrix, int flags)
實際應用範例——讓一個物件沿著路徑移動:
public void goPathAnim(long duration) {
ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, mPathMeasure.getLength());
valueAnimator.setDuration(duration);
valueAnimator.addUpdateListener(new AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float value = (Float) animation.getAnimatedValue();
// 取得當前 Path 上指定距離的座標點,供 onDraw() 使用
mPathMeasure.getPosTan(value, mCurrentPosition, null);
postInvalidate();
}
});
valueAnimator.start();
}
Paint、Canvas、Path、PathMeasure 這四塊拼起來,就是 Android 自定義 View 繪製的全貌。這些 API individually 都不難,真正的門檻在於組合與實戰——只有畫得夠多,才會知道哪個效果該用 Shader、哪個該用 Xfermode、哪個用 Path 更省事。
最後三點實務提醒:
BlurMaskFilter、EmbossMaskFilter、clipPath 搭配抗鋸齒等效果在硬體加速下無效,記得用 setLayerType(View.LAYER_TYPE_SOFTWARE, null)。Picture 與 PictureDrawable 在硬體加速開啟時失效。save()。
Android 介面開發實用技巧:EditText 與常用控件這樣玩
日常開發中,一些看似瑣碎的控件問題往往最耗時間。本文整理了八個實用技巧,從日期輸入的驗證難題、TextView 的富文本呈現,到版面效能的優化,都是可以直接抄進專案的做法
Android Activity 生命週期完整解析(含 onXxx 回呼與三種狀態)
Android Activity 生命週期完整解析(含 onXxx 回呼與三種狀態) 新建一個專案,MainActivity 的程式碼如下,我們藉由它來觀察各個生命週期方
Android Menu 選單實作:程式碼動態建立與 XML 宣告兩種寫法
選項選單(Options Menu)是 Android 早期版本最典型的操作入口。雖然後來被 Action Bar 與 Toolbar 的設計取代,但理解它的運作機制,仍
Android 常用命令行:ADB 環境配置與指令整理
Android 常用命令行:ADB 環境配置與指令整理 ADB 是 Android 開發與除錯的重要工具,可用來安裝應用、傳輸檔案、查看日誌與進入裝置 shell。本文整