1.畫水平虛線
直接建一個shape,設置stroke屬性就行了,再將這個屬性直接作為background的drawable屬性引入就行了
注意在4.0以上的真機加一句
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="line">
<solid android:color="@color/red"></solid>
<stroke
android:dashWidth="10dp" //虛線的小線段長度
android:dashGap="10dp" //間隔距離
android:color="@color/app_color"
android:width="4dp"
/>
</shape>
<View
android:id="@+id/content"
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_gravity="center_vertical"
android:background="@drawable/dottde_line"
android:layerType="software" /> //4.0以上的加,不然真機中是實線
2.畫豎直虛線
這里借鑒一個 rotate屬性去實現,代碼如下
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:left="-30dp"
android:right="-30dp">
<rotate
android:drawable="@drawable/dottde_line"
android:visible="true"
android:fromDegrees="90">
</rotate>
</item>
</layer-list>
<View
android:id="@+id/content_2"
android:layout_width="30dp"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:background="@drawable/dottde_v_line"
android:layerType="software" />
原理:
設置了fromDegress之后,會先畫一條水平虛線,然后再瞬間順時針旋轉90度角,但是單這樣還不行,因為我的view的寬度設置的是2dp,高度是match_parent,發現出來的只有一個點,郁悶了。
之前說過,他的原理是先畫一條水平線,然后再旋轉,那么view的寬度只有2dp,他就只能畫2dp,所以旋轉后也就是一個點。因此用item的可以設置偏移量的屬性,我們將rotate節點放於一個item節點下面,然后給item設置左右都為-30dp的偏移量,這樣他在先畫水平線的時候,由於負的偏移量(就和負的margin一樣),就可以畫出60dp長的線,然后再旋轉,就可以得到一條豎直虛線。
3用自定義view去畫
public class DashedLineView extends View{
public Context ctx;
public DashedLineView(Context context, AttributeSet attrs) {
super(context, attrs);
ctx=context;
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
Paint paint = new Paint();
paint.setStyle(Paint.Style.STROKE);
paint.setColor(getResources().getColor(R.color.red));
paint.setStrokeWidth(dip2px(ctx,2));
Path path = new Path();
path.moveTo(0, 0);
path.lineTo(0, 900);
PathEffect effects = new DashPathEffect(new float[]{6, 4, 4, 4}, 2);
paint.setPathEffect(effects);
canvas.drawPath(path, paint);
}
/**
* 根據手機的分辨率從 dp 的單位 轉成為 px(像素)
*/
public static int dip2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
}
原理:
4.認識圖層列表
地址 https://developer.android.google.cn/guide/topics/resources/drawable-resource.html?hl=zh-cn#LayerList