Android沿路径移动对象

时间:2011-05-27 15:23:45

标签: android animation path geometry

我创建了一个圆形路径,并在屏幕上显示它们如下:

public void onDraw(Canvas canvas){

        Path sPath = new Path();
        sPath.moveTo(100, 100);
        sPath.lineTo(300, 100);
        sPath.lineTo(300, 300);
        sPath.lineTo(100,300);
        sPath.lineTo(100,100);
        sPath.close();

        Paint ballPaint = new Paint();
        ballPaint.setColor(Color.GREEN);
        Paint pathPaint = new Paint();
        pathPaint.setColor(Color.BLUE);

        canvas.drawPath(sPath, ballPaint);
        canvas.drawCircle(100,100,20,pathPaint);
    }

我想让圆圈沿着路径移动,我该怎么做?

5 个答案:

答案 0 :(得分:16)

是的,可以沿路径移动图像。我将提供简单的解决方案来展示原理。以下代码将沿路径设置圆圈的动画。

int iCurStep = 0;// current animation step

@Override
protected void onDraw(Canvas canvas) {
    PathMeasure pm = new PathMeasure(sPath, false);
    float fSegmentLen = pm.getLength() / 20;//we'll get 20 points from path to animate the circle
    float afP[] = {0f, 0f};

    if (iCurStep <= 20) {
        pm.getPosTan(fSegmentLen * iCurStep, afP, null);
        canvas.drawCircle(afP[0],afP[1],20,pathPaint);
        iCurStep++;
        invalidate();
    } else {
        iCurStep = 0;
    };
};

答案 1 :(得分:14)

以下是我使用的动画师:

目的:沿路径“路径”移动视图“视图”

V21 +:

ValueAnimator pathAnimator = ObjectAnimator.ofFloat(view, "x", "y", path)

V11 +:

ValueAnimator pathAnimator = ValueAnimator.ofFloat(0.0f, 1.0f);

pathAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
float[] point = new float[2];

@Override
    public void onAnimationUpdate(ValueAnimator animation) {
        float val = animation.getAnimatedFraction();
        PathMeasure pathMeasure = new PathMeasure(path, true);
        pathMeasure.getPosTan(pathMeasure.getLength() * val, point, null);
        view.setX(point[0]);
        view.setY(point[1]);
    }
});

答案 2 :(得分:6)

v21 +:这会在路径上创建二次贝塞尔曲线,并沿着它动画myView。

final Path path = new Path();
path.quadTo(controlX, controlY, finalX, finalY);
ObjectAnimator.ofFloat(myView, View.X, View.Y, path).start();

答案 3 :(得分:3)

你需要将每一帧的圆圈向下移动到下一个航点,并在它到达那里后进行检测,然后开始朝下一个方向移动。我所知道的没有内置系统。

答案 4 :(得分:0)

正确的方法是使用ContraintLayout,然后在要设置动画的路径上的点之间添加关键帧,如此处所述:https://medium.com/google-developers/defining-motion-paths-in-motionlayout-6095b874d37