Good day. You need to dynamically draw a polygon in android on canvas. I do like this, but nothing comes out !!! Where is the mistake?

@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); path.moveTo(startX,startY); for (i=0;i<x.length;i++){ x[i]=startX; y[i]=startY; path.lineTo(x[i], y[i]); path.close(); canvas.drawCircle(x[i], y[i], 20, paint); } canvas.drawPath(path,paint); } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()){ case MotionEvent.ACTION_DOWN: startX= event.getX(); startY= event.getY(); break; case MotionEvent.ACTION_UP: break; case MotionEvent.ACTION_MOVE: break; default: return false; } invalidate(); return super.onTouchEvent(event); } 
  • path.close() probably should not be called in a loop, but before drawing. Although everything is generally sad. You need to store the index of the next point in the array in the array, fill it with coordinates in onTouch , increase the index, and in onDraw draw from x[0], y[0] to the end. It may be better to use lists instead of arrays. - zRrr

1 answer 1

Draw it out! But how to assign and sign each corner a number or letter!?

code how to draw a polygon ...

  @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: if (i == 0) { startX = event.getX(); startY = event.getY(); x[i] = startX; y[k] = startY; path.moveTo(x[i], y[k]); path.addCircle(x[i], y[k], 20, Path.Direction.CCW); } else { x[i] = event.getX(); y[k] = event.getY(); moveY = y[i]; moveX = x[k]; if (startX > moveX - Rad && startX < moveX + Rad && startY > moveY - Rad && startY < moveY + Rad) { path.lineTo(startX, startY); path.close(); invalidate(); return false; } else { path.lineTo(x[i], y[k]); path.addCircle(x[i], y[k], 15, Path.Direction.CCW); } } i++; k++; } } invalidate(); return true; }