我想创建一个这样的屏幕:
我必须用线条(如果可能的话,虚线)将宽度和高度分成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);
}
}
}
}
答案 0 :(得分:2)
将Paint.setpathEffect(PathEffect effect)与DashPathEffect一起使用。
来自docs:interval数组必须包含偶数个条目(&gt; = 2),偶数索引指定&#34; on&#34;间隔和奇数索引指定&#34; off&#34;间隔。
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);