3

我正在研究动态壁纸。但首先我必须学习画布动画。我这里有一个可以正常工作的代码。它使用 math.random()。但我想要的是这样的。 在此处输入图像描述

在这里,我希望图像像上面所示的路径一样移动。我的想法是对 x 和 y 使用 math.random。但是使用它的问题是图像会出现在屏幕的任何地方。我想要图像,以创建随机路径。我知道它关于 x 和 y 坐标,但我想不出路径将如何随机触发?我实际上无法解释它。但是如果你知道弹跳球,球有一个随机坐标。就这样。这是我的代码。

public class MainActivity extends Activity {

    private Game game;
     public Handler updateHandler = new Handler(){
            /** Gets called on every message that is received */
            // @Override
            public void handleMessage(Message msg) {
                game.update();
                game.invalidate();
                super.handleMessage(msg);
            }
        };
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        game = new Game(this);
        setContentView(game);

        Thread myThread = new Thread(new UpdateThread());
        myThread.start();
    }

    public class UpdateThread implements Runnable {

        @Override
        public void run() {

             while(true){
                 try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                 MainActivity.this.updateHandler.sendEmptyMessage(0);
            }
        }

    }

}


public class Game extends View {

    private Bitmap image;
    private Paint paint;
    private int x=0;

    public Game(Context context) {
        super(context);
        image = Bitmap.createBitmap(BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_launcher));
        paint = new Paint();
    }

    // called every Frame
    protected void onDraw(Canvas canvas) {

        canvas.drawBitmap(image, x, 0, paint);
    }

    // called by thread
    public void update() {
            x = 1;
            x += Math.random() * 100;

    }

}

我希望你能在这里帮助我。谢谢。

4

1 回答 1

4

这是无限线性插值循环的代码(您可能希望稍后将其更改为平滑曲线);

PointF mImagePos = new PointF();
PointF mImageSource = new PointF();
PointF mImageTarget = new PointF();
long mInterpolateTime;

protected void onDraw(Canvas canvas) {
    canvas.drawBitmap(image, mImagePos.x, mImagePos.y, paint);
}

public void update() {
    final long INTERPOLATION_LENGTH = 2000;
    long time = SystemClock.uptimeMillis();
    if (time - mInterpolateTime > INTERPOLATION_LENGTH) {
        mImageSource.set(mImageTarget);
        mImageTarget.x = (float)(Math.random() * 100);
        mImageTarget.y = (float)(Math.random() * 100);
        mInterpolateTime = time;
    }

    float t = (float)(time - mInterpolateTime) / INTERPOLATION_LENGTH;
    // For some smoothness uncomment this line;
    // t = t * t * (3 - 2 * t);

    mImagePox.x = mImageSource.x + (mImageTarget.x - mImageSource.x) * t;
    mImagePos.y = mImageSource.y + (mImageTarget.y - mImageSource.y) * t;
}
于 2012-09-01T08:51:13.363 回答