編輯:關於 Android 程式設計
這篇拖了很久的文章,算是對自己上半年的一個交代。起因是有朋友希望整理一份 Android Canvas 的相關總結,結果一放就放掉了;最近又有人催更,於是就有了這篇「超級基礎」的文章——基礎到什麼程度?基本就是「把 API 用熟就會了」的程度。但別小看這件事,Android 所有內建控件,無非都是在這些 API 之上搭出來的。

溫馨提示:文章很長,建議分小節閱讀。
自定義繪制的第一步,是重寫這個方法:
protected void onDraw(Canvas canvas) { }
它的形參 Canvas(android.graphics.Canvas)本質上就是一塊畫布:我們可以設定它的屬性,也可以在上面畫任何東西。
這個 canvas 的由來,要從 View 的繪製流程說起。整棵 View 樹的繪圖流程是在 ViewRootImpl.performTraversals() 中觸發的;該方法會依先前設定的狀態,判斷是否需要重新計算大小(measure)、重新擺放位置(layout)、以及重繪(draw)。ViewRootImpl 內部有一個 Surface 成員,觸發重繪時會把這個 Surface 的 Canvas 透過 draw 方法遞歸傳遞,從 ViewGroup 一路派發到最末端 View 的 onDraw(Canvas canvas)。
當我們把自定義邏輯畫在這個 Canvas 上,系統框架便會透過 SurfaceFlinger 服務,把測量、布局、繪製後的 Surface 渲染到螢幕上(這個過程相當複雜,不在本文範圍)。
有了畫布,還得有筆。Paint 繼承自 Object,屬於 graphics 家族,有一個子類 TextPaint——例如要實作文字換行時,用 StaticLayout 搭配 TextPaint 會輕鬆得多,沒必要自己手算一堆行距。
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
FontMetrics 是文字定位的關鍵,相關方法有一整組:
float getFontMetrics(Paint.FontMetrics metrics):回傳行間距;metrics 不為 null 時順便填入數值。Paint.FontMetrics getFontMetrics():回傳 FontMetrics 物件。Paint.FontMetricsInt getFontMetricsInt() / int getFontMetricsInt(Paint.FontMetricsInt fmi):與上相同,只是數值型別為 int。
看圖就明白:canvas.drawText() 傳入的 y 其實是圖中的 base 基線,文字座標是以基線為參考。其中:
所以:文字高度 = ascent() + descent(),文字寬度 = measureText(text)。ascent 與 descent 都是負向/正向偏移,忘記加負號是常見的對齊 bug 來源。
其他文字度量方法:
float ascent() / float descent():取得基線到最高/最低字元的距離。void getTextBounds(char[] text, int index, int count, Rect bounds) 與 void getTextBounds(String text, int start, int end, Rect bounds):把文字實際佔用的矩形寫進 bounds,是置中與邊框計算最可靠的方式。float measureText(String text) 及 CharSequence、char[] 的多個重載版本:測量文字寬度。int getTextWidths(...):取得每個字元的獨立寬度陣列,可用於逐字排版。Locale getTextLocales() / void setTextLocale(Locale):文字語系環境。isSubpixelText() / setSubpixelText(boolean):子像素 positioning,讓文字排版更精細。isFakeBoldText() / setFakeBoldText(boolean):偽粗體。isLinearText() / setLinearText(boolean):是否使用線性文字。開啟時不建立文字快取,並會自動開啟 TextScaleX 的額外度量,適合動畫場合。void getTextPath(char[] text, int index, int count, float x, float y, Path path) 與 String 版本:把文字輪廓轉成 Path,可做文字特效。Path path = new Path(); mPaint.getTextPath(STR, 0, STR.length(), 0, 800, path); path.close(); // 特別注意:一定要 close,否則無效 mPaint.setColor(Color.RED); mPaint.setStrokeWidth(5); canvas.drawPath(path, mPaint);
狀態管理:void reset() 清空畫筆復位;void set(Paint src) 用外部 Paint 覆蓋目前設定。
getFlags() / setFlags(int):設定 Paint 的各項旗標,可取值 ANTI_ALIAS_FLAG、DITHER_FLAG、FILTER_BITMAP_FLAG、FAKE_BOLD_TEXT_FLAG、LINEAR_TEXT_FLAG、SUBPIXEL_TEXT_FLAG、UNDERLINE_TEXT_FLAG、STRIKE_THRU_TEXT_FLAG、HINTING_ON / OFF 等。多個旗標可用位元 OR 合併。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_OR_STROKE(實心+空心)。注意在 STROKE 與 FILL_OR_STROKE 模式下,外輪廓位置會向外擴張,這會影響精細對齊。getStrokeWidth() / setStrokeWidth(float):線寬,僅在 STROKE 或 FILL_OR_STROKE 下有效。clearShadowLayer() / setShadowLayer(float radius, float dx, float dy, int shadowColor):陰影層。想幫圓形加一圈擴散光暈就可以用它。Shader getShader() / Shader setShader(Shader shader) 是 Paint 裡最強的一組方法。Shader 的直接子類有:
Shader 基類有一個 Shader.TileMode 列舉:CLAMP 是拉伸最後一個像素鋪滿、REPEAT 類似電腦桌布不足處重複放置、MIRROR 是不足處鏡像翻轉平鋪。此外還提供 boolean getLocalMatrix(Matrix localM) 與 void setLocalMatrix(Matrix localM) 兩個矩陣變換方法。
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 組合渲染:類似動畫裡的組合動畫,可以把上面幾種混搭。
/** mode 使用 Xfermode 物件 */ public ComposeShader(Shader shaderA, Shader shaderB, Xfermode mode) /** mode 使用 PorterDuff.Mode 物件 */ public ComposeShader(Shader shaderA, Shader shaderB, PorterDuff.Mode mode)
Xfermode getXfermode() / Xfermode setXfermode(Xfermode) 同樣是重量級方法。正常情況下,在既有圖像上作畫會完全遮住底圖;setXfermode() 就是拿來定義「疊加時該怎麼算」的規則,傳 null 可清除之前的設定。
// canvas 上原有的圖片叫做 dst // 新畫上去的圖片叫做 src Canvas canvas = new Canvas(dstBitmap); paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); canvas.drawBitmap(srcBitmap, 0f, 0f, paint);

Xfermode 有三個子類,其中兩個已被標記為 Deprecated,重點放在第三個:
(1)AvoidXfermode:指定一個顏色與容差值,控制 Paint 是否在該顏色範圍內繪製或不繪製。
/** * opColor 要匹配的目標顏色 * tolerance 容差值。0 為最小容差(必須完全一樣才匹配),255 為最大容差(略有相近即匹配) * mode 有兩個可取枚舉值: * Avoid —— 只在目標像素與 opColor 匹配成功處「不」繪製 * Target —— 只在目標像素與 opColor 匹配成功處繪製 */ public AvoidXfermode(int opColor, int tolerance, Mode mode)
// !!! 由於高版本 API 已 Deprecated,必須關閉硬體加速才有效果 !!! // 例子:把紅色五角星變成保持背景不變的黑色五角星 // 這個思路可以用來做手勢驅動的漸變效果, // 例如微信底部 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); // 疊上色塊完成替換
(2)PixelXorXfermode:覆蓋既有像素時進行 XOR 運算。
PixelXorXfermode(int opColor)
核心就是 opPixColor ^ srcPixColor ^ dstPixColor,效果較為特殊,實務上少用。
(3)PorterDuffXfermode:最強大的一支,透過 PorterDuff 規則控制 Paint 如何與既有 Canvas 圖像做圖層疊加。

PorterDuff.Mode 提供十六種(後續版本更多)枚舉值。理解方式很簡單:Sa 是來源 alpha、Da 是目標 alpha、Sc 是來源色值、Dc 是目標色值,兩者進行像素運算就得到結果。圓形水波紋進度條、文字進度條、橡皮擦、刮刮樂……這些效果背後都是它。
MaskFilter getMaskFilter() / MaskFilter setMaskFilter(MaskFilter) 針對 Alpha 通道做處理(ColorFilter 則是針對 RGB)。MaskFilter 本身沒有實作,我們用的是它的兩個子類。
BlurMaskFilter 模糊遮罩:
// 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); paint.setMaskFilter(new BlurMaskFilter(20, BlurMaskFilter.Blur.NORMAL)); canvas.drawRect(rect, paint);

更實用的技巧是先抽出圖片的 Alpha 通道,再模糊陰影,最後疊上原圖:
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher); Bitmap bitmapAlpha = bitmap.extractAlpha(); // 提取 Alpha 通道 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);

PathEffect getPathEffect() / PathEffect setPathEffect(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);
/**
* 與 DashPathEffect 類似,但可自定義虛線的形狀
* 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);
}

ColorFilter getColorFilter() / ColorFilter setColorFilter(ColorFilter)。前面 MaskFilter 管 Alpha,這裡管顏色。各種美圖 App 的濾鏡效果,功勞多半在這裡。
(1)ColorMatrixColorFilter:透過顏色矩陣改變像素色值(不含 Alpha)。由於每個像素以 RGBA 形式載入記憶體,Android 用 ColorMatrix 這個 5×4 矩陣(每一行對應 R、G、B、A 之一)來做變換。

而每個像素的展示效果取決於一個 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 矩陣 public ColorMatrixColorFilter(ColorMatrix matrix) // 直接傳入一維陣列(5x4 = 20 個元素) 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();
}
傳入不同參數就能得到老照片、QQ 線上/離線頭像變色等各種效果。
(2)LightingColorFilter:曝光顏色濾鏡。
/** mul (colorMultiply) 色彩倍增,0xAARRGGBB
add (colorAdd) 色彩添加,0xAARRGGBB */
public LightingColorFilter(int mul, int add)
mPaint.setColorFilter(new LightingColorFilter(0xFF00FFFF, 0x0000FF00));
套用到 Bitmap 上會濾掉紅色、加強綠色。計算方式就是 (mul × 原色值 + add) % 255。注意它不處理 Alpha,只對 RGB 有效。
(3)PorterDuffColorFilter:圖層混合顏色濾鏡。
// color 為 0xAARRGGBB 顏色值 // mode 為 PorterDuff.Mode 混合模式 public PorterDuffColorFilter(int color, PorterDuff.Mode mode)
本質就是把畫布上的像素與我們設定的 color 以 mode 方式疊加。同一套 PorterDuff.Mode 既能用於圖形疊加裁剪,也能用於色彩混合,這也是它強大的原因。
買好了這一盒彩筆,也試過各種色彩特性,接下來該拿一張畫紙來畫了。
Canvas() / Canvas(Bitmap bitmap):建構子。自定義 View 通常由上層傳入;單獨 new 出來的 Canvas() 常與 setBitmap() 搭配。參數 Bitmap 必須是 mutable 可變的。setBitmap(Bitmap bitmap):設定可變化的位圖,常用於取得一張 Bitmap 後做離屏處理。getDensity() / setDensity(int):畫布密度,預設為 Bitmap 的密度或 DENSITY_NONE。getHeight() / getWidth():畫布高與寬。isHardwareAccelerated():是否開啟硬體加速,可在 View 或 Activity 層級控制。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));
畫線
/** 將兩點連接成一條線 */
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 都是輔助類,用四個點描述矩形,差別只在精度(float 與 int)。
畫圓角矩形
/** 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)
線條的樣式、顏色、線寬都由 Paint 控制(平滑或折線、虛線或實線),Path 決定形狀。
畫水平文字
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)
沿路徑畫文字
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(char[] text, int index, int count, float[] pos, Paint paint) drawPosText(String text, 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) /** * src 指定裁截區域,null 則不裁剪 * dst 裁剪後在 canvas 中顯示的區域,src 會縮放適應 dst */ 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)
前面介紹 ColorFilter 時提過 ColorMatrix 是處理色度的,而這裡的 Matrix 是處理形狀變換:
setTranslate(float dx, float dy) // 平移 setRotate(float degrees, float px, float py) // 旋轉,px/py 為軸心 setScale(float sx, float sy, float px, float py) // 縮放,px/py 為軸心 setSkew(float kx, float ky) // 傾斜
網格扭曲繪製
/**
* bitmap 原位圖
* meshWidth 橫向劃分為多少格
* meshHeight 縱向劃分為多少格
* verts 長度為 (meshWidth+1) * (meshHeight+1) * 2 + vertOffset 的陣列,
* 記錄扭曲後各頂點位置,每兩個數值表示一個座標
* vertOffset verts 從第幾個元素開始作用
* colors 作用於頂點的顏色陣列,一般為 null
* colorOffset colors 從第幾個數值開始
*/
drawBitmapMesh(Bitmap bitmap, int meshWidth, int meshHeight, float[] verts,
int vertOffset, int[] colors, int colorOffset, Paint paint)
拉簾效果、Mac 關閉網頁的吸入動畫都靠它,原理是按網格重新拉伸圖像。
更通用的版本
drawVertices(Canvas.VertexMode mode, int vertexCount, float[] verts, int vertOffset,
float[] texs, int texOffset, int[] colors, int colorOffset,
short[] indices, int indexOffset, int indexCount, Paint paint)
Picture:記錄而非渲染
drawPicture(Picture picture) drawPicture(Picture picture, RectF dst) drawPicture(Picture picture, Rect dst)
Picture 位於 android.graphics.Picture,相對 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); // canvas.drawBitmap(); 等等一堆畫線畫字畫圖操作 // 注意:這些操作都是基於 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(Path path) clipPath(Path path, Region.Op op)
(注意:開啟硬體加速無效)在深入 Region.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) /* 組合(都與 Op 有關) */ 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 // 最終區域為兩者相交的部分 Region.Op.INTERSECT // 最終區域為兩者合併後的全部 Region.Op.UNION // 最終區域為兩者相交「以外」的部分 Region.Op.XOR // 與 DIFFERENCE 相反(region2 減 region1) Region.Op.REVERSE_DIFFERENCE // 最終區域就是 region2 Region.Op.REPLACE
依矩形裁剪
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(float left, float top, float right, float bottom, Region.Op op) clipRect(Rect rect)
依 Region 裁剪
clipRegion(Region region) clipRegion(Region region, Region.Op op)
取得裁剪邊界
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 的兩個值: // AA —— 考慮抗鋸齒時邊緣處四捨五入 // 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() save(int saveFlags) getSaveCount()
把目前狀態壓入堆疊。getSaveCount() 回傳堆疊中已保存的次數,其回傳值可直接傳給 restoreToCount(),用來回到某一個特定的 save 狀態。有參數的 save 則用來指定 restore 時哪些屬性需要還原。
典型用法:先 save 記住目前位置 → 旋轉平移後畫一些圖形 → restore 回到剛才保存的位置。
restore() restoreToCount(int saveCount)
還原畫布狀態,回到不可逆操作之前。
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() 來控制:
// View 以一般方式繪製,不使用離屏緩衝(預設) LAYER_TYPE_NONE // 開啟硬體加速時繪製到硬體紋理中,否則等同 SOFTWARE LAYER_TYPE_HARDWARE // 繪製到一張 Bitmap 中 LAYER_TYPE_SOFTWARE
硬體加速模式下,Canvas 的 drawXXX 在離屏 layer 上的操作效果是在 View 的 invalidate() 時才生效。因此做動畫或漸變時用 GPU 操作反而更有效率,可以省下大量重複繪製。
實務建議:當你自定義 View,或對既有 View 做動畫、漸變等特效時,先在操作前設為 View.LAYER_TYPE_HARDWARE,完成後改回 View.LAYER_TYPE_NONE。特別是連續變更 alpha、x、y、translationX/Y、scaleX/Y、pivotX/Y、rotation、rotationX/Y 這些屬性時,其實就是在間接操作 layer——這也正是動效看起來卡頓的常見原因。
Path 只能算輔助工具類,但搭配 PathEffect 能做出很炫的效果。
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 類似,但基於上一點相對作畫 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)
參數與 Canvas 的對應方法幾乎一致,唯一新的是 Path.Direction:
// 建立逆時針方向的圖形路徑 Path.Direction.CCW // 建立順時針方向的圖形路徑 Path.Direction.CW
方向主要影響動畫沿路徑行進的方向,單純靜態繪製看不出差別。
offset(float dx, float dy, Path dst) // 平移 Path 或指定的 dst offset(float dx, float dy) reset() // 清空路徑中的所有資訊 rewind() // 清除所有直線曲線,但保留內部資料結構以便重用(效能更好) getFillType() / setFillType(Path.FillType ft)
FillType 的四個值:
// 預設值,兩圖形相交時正常相交顯示 FillType.WINDING // 取 Path 所在且不相交的區域 FillType.EVEN_ODD // 取 Path 的外部區域 FillType.INVERSE_WINDING // 取 Path 外部與相交的區域 FillType.INVERSE_EVEN_ODD
isInverseFillType() // 是否為逆填充模式 toggleInverseFillType() // 切換逆填充狀態 isEmpty() // 不含任何線條曲線時回傳 true isRect(RectF rect) // 是否為矩形;若為 true 且 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,dst 為 null 則存入自身 transform(Matrix matrix)
二次貝茲(quadTo):只有一個控制點。
/** * (x1, y1) 是控制點,(x2, y2) 是結束點 * 若沒有先 moveTo 指定起點,起點默認為 (0, 0) */ quadTo(float x1, float y1, float x2, float y2) // 相對版本 rQuadTo(float dx1, float dy1, float dx2, float dy2) // 例子:平滑曲線 mPath.quadTo(100, 500, 300, 800); canvas.drawPath(mPath, mPaint);

三次貝茲(cubicTo):兩個控制點,可做出更複雜的 S 形。
/** * (x1, y1) 第一控制點,(x2, y2) 第二控制點,(x3, y3) 結束點 */ cubicTo(float x1, float y1, float x2, float y2, float x3, float y3) // 相對版本 rCubicTo(float x1, float y1, float x2, float y2, float x3, float y3) // 例子:平滑曲線 mPath.cubicTo(100, 80, 200, 200, 300, 300); canvas.drawPath(mPath, mPaint);

Path 本質上就是一個封裝路徑數值的工具類,單獨看沒什麼奧妙,用熟即可。
Paint 也吹了、Canvas 也玩了、Path 也搞了——但真正厲害的動畫還需要一個搭檔。PathMeasure 的強大之處在於:不管多複雜的 Path,在它眼裡都只是「一條線」,因此能沿路徑取長度、取座標、取切線。
PathMeasure() // 建立空的 PathMeasure PathMeasure(Path path, boolean forceClosed) // forceClosed 決定是否 close() 這個 path setPath(Path path, boolean forceClosed) // 效果等同上面的建構子 getLength() // 測量 Path 的長度 isClosed() // 輪廓是否為閉環 nextContour() // 移動到下一個輪廓;Path 由多個輪廓組成時使用 getMatrix(float distance, Matrix matrix, int flags) /** * 傳入一個距離(0 <= distance <= getLength()), * 自動計算該距離處的座標點與切線值,分別存入 pos 與 tan */ getPosTan(float distance, float[] pos, float[] tan) /** * 傳入開始與結束距離(0..getLength()), * 回傳這段區間對應的 Path 到 dst * startWithMoveTo 決定起始點是否以 moveTo 為參照 */ getSegment(float startD, float stopD, Path dst, boolean startWithMoveTo)
把 PathMeasure 與 ValueAnimator 結合,就能做出「沿著路徑移動」的動畫:
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();
}
這些 API 單看每一個都不難,真正的門檻在於「知道什麼時候該用哪一個」。畫圓形頭像想到 BitmapShader + drawCircle,做刮刮樂想到 PorterDuffXfermode,做流動虛線想到 DashPathEffect + phase 動畫,做吸附效果想到 PathMeasure + getPosTan——把這些組合形成肌肉記憶,自定義 View 就沒有什麼能難住你了。剩下的,就是多寫幾個 Demo。
Android WebView 線性進度條元件實作詳解
本文拆解一個可直接複用的線性載入進度條元件,效果就是我們在瀏覽器上常見的那種細長進度條。 一、進度條樣式:wevbview_progressbar.xml <l
關於 Android 生命週期,你可能忽略的兩個細節
Android 生命週期大概是連初學者都耳熟能詳的知識,但這裡拋出兩個問題,或許你從沒細想過,甚至可能存在一些理解上的偏差。一、A 啟動 B 時,兩者的生命週期執行順序為
五分鐘把你的 Android Library 發佈到 JCenter
android-library-publish-to-jcenter 這個專案把發佈流程需要的 Gradle 腳本都封裝好了,你只要填幾個屬性,就能在五分鐘內把自己的 A
Android 基礎入門:ViewFlipper 翻轉視圖的基本用法
本節介紹 ViewFlipper,它是 Android 自帶的多頁面管理控件,還能自動播放。和 ViewPager 一次顯示一頁不同,ViewFlipper 是一層層堆疊