How to animate a path on canvas - android

前端 未结 3 1430
醉酒成梦
醉酒成梦 2020-11-28 05:19

Is possible to attach an animator to a path? Is there any other way to draw on canvas animated lines? I searched this before i post , but there is nothing about this. In two

3条回答
  •  孤独总比滥情好
    2020-11-28 05:48

    You can transform your canvas by time, i.e:

    class MyView extends View {
    
        int framesPerSecond = 60;
        long animationDuration = 10000; // 10 seconds
    
        Matrix matrix = new Matrix(); // transformation matrix
    
        Path path = new Path();       // your path
        Paint paint = new Paint();    // your paint
    
        long startTime;
    
        public MyView(Context context) {
            super(context);
    
            // start the animation:
            this.startTime = System.currentTimeMillis();
            this.postInvalidate(); 
        }
    
        @Override
        protected void onDraw(Canvas canvas) {
    
            long elapsedTime = System.currentTimeMillis() - startTime;
    
            matrix.postRotate(30 * elapsedTime/1000);        // rotate 30° every second
            matrix.postTranslate(100 * elapsedTime/1000, 0); // move 100 pixels to the right
            // other transformations...
    
            canvas.concat(matrix);        // call this before drawing on the canvas!!
    
            canvas.drawPath(path, paint); // draw on canvas
    
            if(elapsedTime < animationDuration)
                this.postInvalidateDelayed( 1000 / framesPerSecond);
        }
    
    }
    

提交回复
热议问题