Code directly
package com.view; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.View; /** * Created by Administrator on 2018/3/9 0009. */ public class DottedLineView extends View { private int pointLength = 25 ; // The length and width of each dot in the dotted line is the width declared in XML private int space = 10 ; // The distance between the points Paint paint ; Rect rect ; public DottedLineView (Context context) { super (context) ; init() ; } public DottedLineView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(); } public DottedLineView (Context context , @Nullable AttributeSet attrs , int defStyleAttr) { super (context , attrs , defStyleAttr) ; init() ; } private void init () { paint = new Paint(Paint. ANTI_ALIAS_FLAG ) ; // Anti-aliasing paint .setColor(Color. parseColor ( "#000000" )) ; // The color of the dotted line (black) rect = new Rect() ; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); int startLeft=0; int startTop=0; for (int i=0;;i++){ if(i!=0){ startTop=startTop+pointLength+space; } rect.left=startLeft; rect.right=startLeft+getWidth(); rect.top=startTop; rect.bottom=startTop+pointLength; canvas.drawRect(rect,paint); if(rect.bottom>=getHeight()){ //超过View的高度退出循环 return; } } } }
Used in xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <com.view.DottedLineView android:layout_width="3dp" android:layout_height="400dp" android:layout_margin="10dp" android:background="#fff" /> </LinearLayout>
效果图
其中一些数值我写死在类里面了 没有做动态设置