標籤:
用到的工具類:
DashPathEffect
android中對該類的說明如下:
翻譯一下就是:
第一個參數intervals數組必須是偶數個元素(個數>=2),偶數下標代表實線,奇數下標代表空白長度
第二個參數phase:向左位移量(位移量=phase mod (intervals數組各項之和), 即取餘運算)
注意:只有當Paint的style設定為STROKE或者FILL_AND_STROKE時才能繪製出虛線效果,如果Paint的style設定為FILL時是不會起作用的。
/** * 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); }
初始化paint, Path
private Paint mDottedLinePaint;private Path mDottedPath;// 虛線paintmDottedLinePaint = new Paint();mDottedLinePaint.setColor(getResources().getColor(R.color.horizontal_bar_chart_dot_line_color));mDottedLinePaint.setStyle(Style.STROKE);mDottedLinePaint.setStrokeWidth(2);PathEffect effects = new DashPathEffect(new float[]{ 10, 5}, 1);//意思是所畫虛線規則是先畫10個長度的實線,留下5個長度的空白mDottedLinePaint.setPathEffect(effects);mDottedPath = new Path();
畫虛線
canvas.drawPath(mDottedPath, mDottedLinePaint);
這裡需要注意,一定要用canvas的drawPath方法,如果用drawLine的話是畫不出效果的,原來在網上找的代碼就是用的drawLine,結果半天出不來效果
android 畫虛線