Android 虛線 分割線
阿新 • • 發佈:2018-11-21
在網上一搜索如何實現Android虛線,絕大部分都說使用shape的方式實現,然後在View節點下開啟軟加速 android:layerType= “software”
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="line" >
<stroke
android:dashGap="3dp"
android:dashWidth ="6dp"
android:width="1dp"
android:color="#63a219" />
<!-- 虛線的高度 -->
<size android:height="1dp" />
</shape>
但是我在好幾款機型上執行結果虛線都顯示不出來,最後只好採用 “畫虛線”實現了,註釋都寫了,應該可以看明白
public class DashLine extends View {
//畫圖路徑
private Path mPath;
//畫筆
private Paint mPaint;
//上下文
private Context mContext;
//距離多少長度畫一次虛線
private int distance = 10;
//可以使paint畫出類似虛線的樣子,指定虛實的排列方式
private PathEffect mPathEffect;
public DashLine(Context context, AttributeSet attrs) {
super(context, attrs);
this.mContext = context;
//初始化畫筆
mPaint = new Paint();
//初始化畫路徑
mPath = new Path();
//DashPathEffect是PathEffect類的一個子類,可以使paint畫出類似虛線的樣子,並且可以任意指定虛實的排列方式
//float陣列,必須是偶數長度,且>=2,指定了多少長度的實線之後再畫多少長度的空白
mPathEffect = new DashPathEffect(new float[]{distance, distance, distance, distance}, 1);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mPaint.reset();
mPaint.setStyle(Paint.Style.STROKE);
//設定畫筆顏色
mPaint.setColor(Color.parseColor("#DCDCE2"));
mPaint.setStrokeWidth(3);
mPath.reset();
//mPath繪製的繪製起點
//path.moveTo(0, 0);
int screenWidth = ((Activity) mContext).getWindowManager().getDefaultDisplay().getWidth();
IMLog.e("tlt [DashLine] 螢幕寬度:" + screenWidth);
//新增一條線從最後一點新增到指定的點(x,y) 如果沒有呼叫moveTo()第一點是自動設定為(0,0)
mPath.lineTo(screenWidth, 0);
mPaint.setPathEffect(mPathEffect);
canvas.drawPath(mPath, mPaint);
}
}