編輯:Android 資訊
先前撰寫 Android Paint 使用詳解時,setPathEffect(PathEffect effect) 這個方法沒有深入展開,本篇就結合程式碼把它講透。
PathEffect 共有六個子類:ComposePathEffect、CornerPathEffect、DashPathEffect、DiscretePathEffect、PathDashPathEffect、SumPathEffect。這些類的程式碼量都不大,下面逐一說明。
它會把 Path 線段之間的尖銳夾角替換成指定半徑的圓角。建構子中的 radius 就是圓角半徑。
/**
* Transforms geometries that are drawn (either STROKE or FILL styles) by
* replacing any sharp angles between line segments into rounded angles of
* the specified radius.
*
* @param radius Amount to round sharp angles between line segments.
*/
public CornerPathEffect(float radius) {
native_instance = nativeCreate(radius);
}
實作程式碼如下,這裡用 8 條 Path 搭配遞增的半徑,方便直接對比效果差異:
public class PathEffectView extends View {
private Paint mPaint;
private int marging = 82;
private CornerPathEffect mCornerPathEffect[];
private Path mPath[];
public PathEffectView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setColor(Color.BLACK);
mPaint.setStyle(Style.STROKE);
mPaint.setStrokeWidth(6);
mCornerPathEffect = new CornerPathEffect[8];
mPath = new Path[8];
for (int i = 0; i < mPath.length; i++) {
Path path = new Path();
path.moveTo(i * marging, marging);
path.lineTo(300 + i * marging, 180);
path.lineTo(400 + i * marging, 600);
path.lineTo(200 + i * marging, 1000);
path.lineTo(110 + i * marging, 1200);
mPath[i] = path;
mCornerPathEffect[i] = new CornerPathEffect(i * 10);
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawColor(Color.WHITE);
for (int i = 0; i < mPath.length; i++) {
mPaint.setPathEffect(mCornerPathEffect[i]);
canvas.drawPath(mPath[i], mPaint);
}
}
}
執行結果:

第一條半徑為 0,尖角完全保留;往後半徑遞增,轉角處的圓潤感越來越明顯。
這是最常用的一個。看官方註解可以掌握兩個重點:intervals 陣列元素個數必須是大於等於 2 的偶數,phase 則是偏移量。
/**
* The intervals array must contain an even number of entries (>=2), with
* the even indices specifying the "on" intervals, and the odd indices
* specifying the "off" intervals. phase is an offset into the intervals
* array (mod the sum of all of the intervals). The intervals array
* controls the length of the dashes. The paint's strokeWidth controls the
* thickness of the dashes.
*
* Note: this patheffect only affects drawing with the paint's style is set
* to STROKE or FILL_AND_STROKE. It is ignored if the drawing is done with
* style == FILL.
*
* @param intervals array of ON and OFF distances
* @param phase offset into the intervals array
*/
public DashPathEffect(float intervals[], float phase) {
if (intervals.length < 2) {
throw new ArrayIndexOutOfBoundsException();
}
native_instance = nativeCreate(intervals, phase);
}
實作程式碼:
public class PathEffectView extends View {
private Paint mPaint;
private int marging = 82;
private DashPathEffect mCornerPathEffect[];
private Path mPath[];
public PathEffectView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setColor(Color.BLACK);
mPaint.setStyle(Style.STROKE);
mPaint.setStrokeWidth(6);
mCornerPathEffect = new DashPathEffect[8];
mPath = new Path[8];
for (int i = 0; i < mPath.length; i++) {
Path path = new Path();
path.moveTo(i * marging, marging);
path.lineTo(300 + i * marging, 180);
path.lineTo(400 + i * marging, 600);
path.lineTo(200 + i * marging, 1000);
path.lineTo(110 + i * marging, 1200);
mPath[i] = path;
mCornerPathEffect[i] = new DashPathEffect(new float[] { 1, 2, 4, 8 }, 1);
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawColor(Color.WHITE);
for (int i = 0; i < mPath.length; i++) {
mPaint.setPathEffect(mCornerPathEffect[i]);
canvas.drawPath(mPath[i], mPaint);
}
}
}
執行結果:

這裡的 phase 偏移量,意思是「從指定長度的位置開始畫」,但線的總長度並不因此改變。我們把 phase 改成遞增值再看一次:
mCornerPathEffect[i] = new DashPathEffect(new float[] { 10, 20, 40, 80 }, i * 10);
執行結果:

節奏是:先畫長度 10 的實線,接著 20 的虛線,然後 40 的實線,最後 80 的虛線。仔細看起始位置,每一條都不一樣,因為各自的偏移量不同;但總長度不變——上面的線只是左右平移,長度並沒有減少。之所以視覺上「越來越短」,其實是巧合:後面的線正好落在虛線區段,肉眼看不到而已。
通俗一點說:線的起點與終點都沒變,線就像一條無限長的繩子,偏移量相當於把繩子往後拽的距離。用 PathMeasure 印一下長度就能驗證:
for (int i = 0; i < mPath.length; i++) {
mPaint.setPathEffect(mCornerPathEffect[i]);
canvas.drawPath(mPath[i], mPaint);
PathMeasure measure = new PathMeasure(mPath[i], false);
Log.d("wld_________", measure.getLength() + "");
}
看 log 就知道,八條線的長度完全相同。

segmentLength 指定切斷的長度,deviation 則是切斷後線段的隨機偏移量上限(實際偏移小於等於 deviation)。
/**
* Chop the path into lines of segmentLength, randomly deviating from the
* original path by deviation.
*/
public DiscretePathEffect(float segmentLength, float deviation) {
native_instance = nativeCreate(segmentLength, deviation);
}
實作程式碼:
public class PathEffectView extends View {
private Paint mPaint;
private int marging = 82;
private DiscretePathEffect mPathEffect[];
private Path mPath[];
public PathEffectView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setColor(Color.BLACK);
mPaint.setStyle(Style.STROKE);
mPaint.setStrokeWidth(6);
mPathEffect = new DiscretePathEffect[8];
mPath = new Path[8];
for (int i = 0; i < mPath.length; i++) {
Path path = new Path();
path.moveTo(i * marging, marging);
path.lineTo(300 + i * marging, 180);
path.lineTo(400 + i * marging, 600);
path.lineTo(200 + i * marging, 1000);
path.lineTo(110 + i * marging, 1200);
mPath[i] = path;
mPathEffect[i] = new DiscretePathEffect(10, 3 * i);
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawColor(Color.WHITE);
for (int i = 0; i < mPath.length; i++) {
mPaint.setPathEffect(mPathEffect[i]);
canvas.drawPath(mPath[i], mPaint);
}
}
}
執行結果:

第一條線偏移量為 0,所以看不出變化。把切斷長度縮到 1、偏移上限維持 3*i 再看:
mPathEffect[i] = new DiscretePathEffect(1, 3 * i);

視覺上有點像磁鐵的感覺。那麼它的實際長度是多少?同樣用 PathMeasure 量一下:
for (int i = 0; i < mPath.length; i++) {
mPaint.setPathEffect(mPathEffect[i]);
canvas.drawPath(mPath[i], mPaint);
PathMeasure measure = new PathMeasure(mPath[i], false);
Log.d("wld__________", measure.getLength() + "");
}
結果頗為不可思議——每條線的長度和之前測的一樣,完全沒變。這也再次印證了 PathEffect 的本質:它只改變「繪製外觀」,不改變 Path 本身的幾何長度。

它和 DashPathEffect 概念相近,差別在於可以用自訂圖形來「蓋章」式的填充 Path。先看源碼:
public enum Style {
TRANSLATE(0), //!< translate the shape to each position
ROTATE(1), //!< rotate the shape about its center
MORPH(2); //!< transform each point, and turn lines into curves
Style(int value) {
native_style = value;
}
int native_style;
}
/**
* Dash the drawn path by stamping it with the specified shape. This only
* applies to drawings when the paint's style is STROKE or STROKE_AND_FILL.
* If the paint's style is FILL, then this effect is ignored. The paint's
* strokeWidth does not affect the results.
*
* @param shape The path to stamp along
* @param advance spacing between each stamp of shape
* @param phase amount to offset before the first shape is stamped
* @param style how to transform the shape at each position as it is stamped
*/
public PathDashPathEffect(Path shape, float advance, float phase, Style style) {
native_instance = nativeCreate(shape.ni(), advance, phase, style.native_style);
}
private static native long nativeCreate(long native_path, float advance, float phase, int native_style);
參數含義:shape 是填充用的圖形,可自行繪製;advance 是相鄰圖形之間的間距;phase 是路徑的偏移量。三種 Style 的差異是:
實作程式碼:
public class PathEffectView extends View {
private Paint mPaint;
private int marging = 82;
private PathEffect mPathEffect1;
private PathEffect mPathEffect2;
private PathEffect mPathEffect3;
private Path mPath;
public PathEffectView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setStyle(Style.STROKE);
mPaint.setStrokeWidth(6);
mPaint.setColor(Color.RED);
mPath = new Path();
mPath.moveTo(0, marging);
mPath.lineTo(300, 180);
mPath.lineTo(400, 600);
mPath.lineTo(200, 1000);
mPath.lineTo(800, 1200);
Path p = new Path();
p.addRect(0, 0, 64, 12, Path.Direction.CCW);
mPathEffect1 = new PathDashPathEffect(p, 128, 0, android.graphics.PathDashPathEffect.Style.MORPH);
mPathEffect2 = new PathDashPathEffect(p, 128, 0, android.graphics.PathDashPathEffect.Style.ROTATE);
mPathEffect3 = new PathDashPathEffect(p, 128, 0, android.graphics.PathDashPathEffect.Style.TRANSLATE);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawColor(Color.WHITE);
mPaint.setPathEffect(mPathEffect1);
canvas.drawPath(mPath, mPaint);
canvas.translate(200, 0);
mPaint.setPathEffect(mPathEffect2);
canvas.drawPath(mPath, mPaint);
canvas.translate(200, 0);
mPaint.setPathEffect(mPathEffect3);
canvas.drawPath(mPath, mPaint);
}
}
執行效果:

自訂了一個矩形作為圖章。前兩組的矩形方向會隨路徑改變,其中 MORPH 那組在轉角連接處呈現平滑過渡,而 TRANSLATE 那組方向固定不變。
接著重點分析後兩個參數。第二個參數 advance 指的是「第一個圖形與第二個圖形起始位置之間的距離」。全部改用 MORPH 模式來測試:
mPathEffect1 = new PathDashPathEffect(p, 0, 0, android.graphics.PathDashPathEffect.Style.MORPH); mPathEffect2 = new PathDashPathEffect(p, 64, 0, android.graphics.PathDashPathEffect.Style.MORPH); mPathEffect3 = new PathDashPathEffect(p, 228, 0, android.graphics.PathDashPathEffect.Style.MORPH);
執行結果:

第一個沒有間距;第二個間距等於矩形寬度 64,因此首尾恰好相連、中間沒有縫隙;最後一個則出現明顯間隙。
再看第三個參數 phase,它與 advance 密切相關:當偏移量介於 1 到 advance 之間時,視覺上的偏移距離逐漸遞減;當偏移量等於 advance 的整數倍時,偏移量歸零;一旦超過 advance,系統會對它取餘數。看程式碼:
private void init() {
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setStyle(Style.STROKE);
mPaint.setStrokeWidth(6);
mPaint.setColor(Color.RED);
mPath = new Path();
mPath.moveTo(0, marging);
mPath.lineTo(300, 180);
mPath.lineTo(400, 600);
mPath.lineTo(200, 1000);
mPath.lineTo(800, 1200);
Path p = new Path();
p.addRect(0, 0, 64, 12, Path.Direction.CCW);
mPathEffect1 = new PathDashPathEffect(p, 128, 128, android.graphics.PathDashPathEffect.Style.MORPH);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawColor(Color.WHITE);
mPaint.setPathEffect(mPathEffect1);
canvas.drawPath(mPath, mPaint);
}
執行結果:

確實沒有偏移,因為 128 正好是 advance 的一倍。把 phase 改成 129 再看:
mPathEffect1 = new PathDashPathEffect(p, 128, 129, android.graphics.PathDashPathEffect.Style.MORPH);
結果:

偏移量達到最大。其實 129 與 1 的效果完全相同,因為 129 對 128 取餘仍是 1。總結規律:偏移量從 1 遞增到 128 的過程中,視覺偏移距離逐漸遞減,而偏移量等於 128 時則完全沒有偏移。
再改一次程式碼:
mPathEffect1 = new PathDashPathEffect(p, 28, 1, android.graphics.PathDashPathEffect.Style.MORPH);
前面分析過,只有當 advance 大於自訂圖形尺寸時才會出現間隙( MORPH 模式下主要看圖形寬度;若 Style 為 TRANSLATE,則 advance 必須大於圖形高度才會出現間隙,這也很好理解)。所以這組設定會得到一條沒有間隙、但有偏移的路徑:

如果把 phase 也改成 28:
mPathEffect1 = new PathDashPathEffect(p, 28, 28, android.graphics.PathDashPathEffect.Style.MORPH);
就會回到完全沒有偏移的狀態,這裡不再貼截圖。
這是一種組合模式,把兩種 PathEffect 的特性疊在一起。先看源碼:
/**
* Construct a PathEffect whose effect is to apply first the inner effect
* and the the outer pathEffect (e.g. outer(inner(path))).
*/
public ComposePathEffect(PathEffect outerpe, PathEffect innerpe) {
native_instance = nativeCreate(outerpe.native_instance, innerpe.native_instance);
}
private static native long nativeCreate(long nativeOuterpe, long nativeInnerpe);
執行順序是 outer(inner(path)):先呈現 innerpe 的特性,再套用 outerpe 的效果。實作程式碼:
public class PathEffectView extends View {
private Paint mPaint;
private int marging = 82;
private PathEffect mEffects[];
private Path mPath;
public PathEffectView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setStyle(Style.STROKE);
mPaint.setStrokeWidth(6);
mPaint.setColor(Color.RED);
mPath = new Path();
mPath.moveTo(0, marging);
mPath.lineTo(300, 180);
mPath.lineTo(400, 600);
mPath.lineTo(200, 1000);
mPath.lineTo(800, 1200);
mEffects = new PathEffect[3];
mEffects[0] = new CornerPathEffect(80);
mEffects[1] = new DashPathEffect(new float[] { 20, 10, 5, 10 }, 0);
mEffects[2] = new ComposePathEffect(mEffects[1], mEffects[0]);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
for (int i = 0; i < mEffects.length; i++) {
mPaint.setPathEffect(mEffects[i]);
canvas.drawPath(mPath, mPaint);
canvas.translate(200, 0);
}
}
}
執行結果:

第一條是純圓角,第二條是純虛線,因此組合出的第三條自然就是「圓角化的虛線」。把組合順序對調:
mEffects[2] = new ComposePathEffect(mEffects[0], mEffects[1]);
執行結果:

視覺上幾乎沒變化。原因在於這次先提取的是第二個效果(虛線),再套第一個(圓角),而圓角半徑 80 相對虛線節奏來說影響不明顯。把虛線節奏放大後再看:
mEffects[1] = new DashPathEffect(new float[] { 200, 10, 5, 10 }, 0);
執行結果:

這時順序差異就明顯了——差別在於圓角是在「虛線切完之後」還是「切虛線之前」套上去的。
最後一個是 SumPathEffect,它把兩種效果分別呈現後再疊在一起。沿用上面的程式碼稍作修改:
mEffects[1] = new DashPathEffect(new float[] { 20, 10, 5, 10 }, 0);
mEffects[2] = new SumPathEffect(mEffects[1], mEffects[0]);
執行效果:

可以看到圓角線與虛線各自獨立呈現後疊合,這正是 Sum 與 Compose 在本質上的差異:Compose 是「先後串接」,Sum 是「同時並存」。
至此,PathEffect 的六種效果全部分析完畢。如果想做出動態效果,只要在 onDraw 中呼叫 invalidate() 持續重繪,並在每次重繪時修改 phase 偏移量即可——虛線就會「跑」起來。
Android UI 元件系列:WebView 網路檢視
Android 的網路功能十分強大,WebView 元件能直接載入網頁,可將其視為一個內建的瀏覽器。要實現這個功能,具體步驟如下: 1、在版面配置檔中宣告 WebView
10款開源的Android任務管理與時間追蹤應用推薦
現代生活的壓力偶爾會把人壓倒,即使再擅長組織的人,也可能需要數字工具來追蹤會議與截止期限。以下精選10款開源的Android應用,能幫你安排時間、記錄任務耗時並避免錯過期
最詳盡的 Android Toolbar 開發實踐與踩坑總結
年前我發過一篇介紹 Translucent System Bar 特性的文章《Translucent System Bar 的最佳實踐》,收到不少開發者的關注和反饋。今天
HTTPS 原理與在 Android 中的實務處理
本文先說明 HTTP 在安全上的先天不足,接著拆解 HTTPS 賴以建立信任的關鍵技術,然後以實際握手封包檢視整個協商過程,最後整理 Android 開發時最常踩到的 H