How to draw a path on an Android canvas with animation?

Viewed 32980

I'm making an Android app and I've got a tricky thing to do. I need to draw a path on a canvas but the drawing should be animated (ie. drawing point after point with a slight delay).

Is it possible to make something like this using Android SDK? If not, how could I produce this effect?

4 Answers

I have made it with ObjectAnimator. We have any Path and our CustomView (in wich we'll draw our path)

    private CustomView view;
    private Path path;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        view = findViewById(R.id.custom_view);
        path = new Path();
        path.moveTo(0f, 0f);
        path.lineTo(getResources().getDimension(R.dimen.point_250), 0f);
        path.lineTo(getResources().getDimension(R.dimen.point_250), getResources().getDimension(R.dimen.point_150));

        findViewById(R.id.btnStart).setOnClickListener(v -> {
            test();
        });
    }

    private void test() {
        ValueAnimator pathAnimator = ObjectAnimator.ofFloat(view, "xCoord", "yCoord", path);
        pathAnimator.setDuration(5000);
        pathAnimator.start();
    }

And just pass our "xCoord" and "yCoord" to CustomView

public class CustomView extends View {

    private Paint paint;
    private float xCoord;
    private float yCoord;

    private Path path = new Path();

    public void setXCoord(float xCoord) {
        this.xCoord = xCoord;
    }

    public void setYCoord(float yCoord) {
        this.yCoord = yCoord;
        path.lineTo(xCoord, yCoord);
        invalidate();
    }

    public CustomView(Context context) {
        super(context);
        init();
    }

    public CustomView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    void init() {
        paint = new Paint();
        paint.setAntiAlias(true);
        paint.setDither(true);
        paint.setColor(Color.BLACK);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeJoin(Paint.Join.ROUND);
        paint.setStrokeCap(Paint.Cap.ROUND);
        paint.setStrokeWidth(20);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        canvas.drawPath(path, paint);

    }

}
Related