我更改了NetCanvas 以绘制一个看起来像您问题中的第二张图片的形状:
public class NetCanvas1 extends View {
Path path0 = new Path();
private Paint p0;
private int points_Num = 20;
private int first_Points_Num = 5;
public NetCanvas1(Context context) {
super(context);
p0 = new Paint();
p0.setShader(new LinearGradient(0, 0, 230, getHeight(), Color.GREEN,
Color.RED, Shader.TileMode.CLAMP));
p0.setStyle(Style.STROKE);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float x0 = event.getX();
float y0 = event.getY();
if (event.getAction() == MotionEvent.ACTION_DOWN) {
path0.moveTo(x0, y0);
path0.lineTo(x0, y0);
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
path0.lineTo(x0, y0);
} else if (event.getAction() == MotionEvent.ACTION_UP) {
path0.lineTo(x0, y0);
invalidate();
}
return true;
}
@Override
public void onDraw(Canvas canvas) {
canvas.drawPath(path0, p0);
FlaotPoint[] pointArray = getPoints();
try {
for (int i = 0; i < first_Points_Num; i++) {
for (int j = i; j < pointArray.length; j++) {
canvas.drawLine(pointArray[i].getX(), pointArray[i].getY(),
pointArray[j].getX(), pointArray[j].getY(), p0);
}
}
path0.reset();
} catch (Exception e) {
}
}
private FlaotPoint[] getPoints() {
FlaotPoint[] pointArray = new FlaotPoint[points_Num];
PathMeasure pm = new PathMeasure(path0, false);
float length = pm.getLength();
float distance = 0f;
float speed = length / points_Num;
int counter = 0;
float[] aCoordinates = new float[2];
while ((distance < length) && (counter < points_Num)) {
// get point from the path
pm.getPosTan(distance, aCoordinates, null);
pointArray[counter] = new FlaotPoint(aCoordinates[0],
aCoordinates[1]);
counter++;
distance = distance + speed;
}
return pointArray;
}
class FlaotPoint {
float x, y;
public FlaotPoint(float x, float y) {
this.x = x;
this.y = y;
}
public float getX() {
return x;
}
public float getY() {
return y;
}
}
}
结果取决于points_Num、first_Points_Num 的值以及与 for 循环中的线连接的点的顺序:
for (int i = 0; i < first_Points_Num; i++) {
for (int j = i; j < pointArray.length; j++) {
canvas.drawLine(pointArray[i].getX(), pointArray[i].getY(),
pointArray[j].getX(), pointArray[j].getY(), p0);
}
}
您可以更改每个变量的值或点的顺序以更改结果。结果可能如下所示:
我的想法很简单:从路径中获取点并用线连接它们。如果您想了解更多关于从路径中获取点的详细信息,请参阅getPoints() 方法,你可以看到 this answer 和它的引用。我希望这对你有帮助。