android – 用虚线自定义显示

我想创建一个这样的屏幕:

我必须用线条(如果可能的话,虚线)将宽度和高度分成8个相等的部分.怎么做?

这是我目前的代码:

@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {        
    super.onCreate(savedInstanceState);

    drawView = new DrawView(this);
    drawView.setBackgroundColor(Color.WHITE);
    setContentView(drawView);
    // setContentView(R.layout.activity_main);

    layout = (LinearLayout) findViewById(R.id.load);

    display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    width = size.x;
    height = size.y;

    equal_parts_width = width/8;
    equal_parts_height = width/8;

    Log.i("", width + " <==> " + height + " == "
        + equal_parts_width + "==" +equal_parts_height );   
}

public class DrawView extends View {
    Paint paint = new Paint();  

    public DrawView(Context context) {
        super(context);         
        paint.setColor(Color.GREEN);
    }

        @Override
        public void onDraw(Canvas canvas) {
            for(int i = 0 ; i < 7 ; i++) {
                canvas.drawLine(0, equal_parts_height*i,
                    width, equal_parts_height*i,  paint);
                canvas.drawLine(equal_parts_width*i, 0,
                    height, equal_parts_width*i,  paint);
            }        
        }
    }
}

最佳答案 使用
Paint.setpathEffect(PathEffect effect)
DashPathEffect.

来自docs:interval数组必须包含偶数个条目(> = 2),偶数索引指定“on”间隔,奇数索引指定“off”间隔.

paint.setPathEffect(new DashPathEffect(new float[]{on, off}, 0));

并将其添加到DrawView构造函数中

public DrawView(Context context) {
    super(context);         
    paint.setColor(Color.GREEN);
    paint.setPathEffect(new DashPathEffect(new float[]{on, off}, 0));
}

编辑完整代码..

public class DrawView extends View {
    Paint paint = new Paint();  

    public DrawView(Context context) {
        super(context);         
        paint.setColor(Color.GREEN);
        paint.setStyle(Style.STROKE);
    }

    @Override
    public void onDraw(Canvas canvas) {  
        float width = canvas.getWidth();
        float height = canvas.getHeight();
        float size = height/(7*2); //just use 14 it's for convenience here
        paint.setStrokeWidth(WIDTH);
        paint.setPathEffect(new DashPathEffect(new float[]{size, size}, 0));
        for(int i = 0 ; i < 7 ; i++) {
            canvas.drawLine(0, size*i,
                width, size*i,  paint);
            canvas.drawLine(size*i, 0,
                height, size*i,  paint);
        }        
    }

}

你应该能够采取这个,只需改变它,以满足你的需要.
您还可以使用此代码创建圆点.

 paint.setStrokeJoin(Paint.Join.ROUND);
 paint.setStrokeCap(Paint.Cap.ROUND);
 paint.setDither(true);
 paint.setAntiAlias(true);
点赞