画布随机运动

时间:2012-09-01 08:08:04

标签: android canvas

我正在研究动态壁纸。但首先我必须研究帆布动画。我这里有一个代码可行。它使用math.random()。但我想要的是这样的。 enter image description here

在这里,我希望图像像上面所示的路径一样移动。我的想法是对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;

    }

}

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

1 个答案:

答案 0 :(得分: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;
}