Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android, move bitmap along a path?

I would like to know if it's possible to select coordinates from a path to draw a bitmap over time, for example, I have an image of a sun, and I would like to move it, over time, along an arc path.

Is there some way to define a path like this and then move along it, so that I don't have to calculate it mathematically?

Thanks.

like image 793
Hamid Avatar asked Nov 30 '22 17:11

Hamid


2 Answers

Yes, it's possible to move image along path. I will provide simple solution to show the principle. The following code will move and rotate your image. If you don't need rotation remove the TANGENT_MATRIX_FLAG flag.

import android.graphics.*;
//somewhere global
int iCurStep = 0;// current step

//don't forget to initialize
Path pathMoveAlong = new Path();
private static Bitmap bmImage = null;

@Override
protected void onDraw(Canvas canvas) {
    Matrix mxTransform = new Matrix();
    PathMeasure pm = new PathMeasure(pathMoveAlong, false);
    float fSegmentLen = pm.getLength() / 20;//20 animation steps

    if (iCurStep <= 20) {
        pm.getMatrix(fSegmentLen * iCurStep, mxTransform,
            PathMeasure.POSITION_MATRIX_FLAG + PathMeasure.TANGENT_MATRIX_FLAG);
        canvas.drawBitmap(bmImage, mxTransform, null);
        iCurStep++;
        invalidate();
    } else {
        iCurStep = 0;
    };
};
like image 59
Eduard Avatar answered Dec 02 '22 07:12

Eduard


Here are the animators I use:

Purpose: Move View "view" along Path "path"

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]);
    }
});

Similar requirement to: https://stackoverflow.com/a/30254715/4344057

like image 27
Dileep P G Avatar answered Dec 02 '22 08:12

Dileep P G