将图像移动到左侧和右侧画布

时间:2014-12-10 19:10:32

标签: android android-canvas android-bitmap

我正在使用Canvas移动图像。

它只移动一侧,它一直向右移动。但是我希望它能够向右和向左移动。

看我的代码:

package com.movingbackground;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class MovingBackGround extends SurfaceView implements
        SurfaceHolder.Callback {
    private Bitmap backGround;

    public MovingBackGround(Context context) {
        super(context);
        backGround = BitmapFactory.decodeResource(context.getResources(),
                R.drawable.ab);
        setWillNotDraw(false);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        doDrawRunning(canvas);
        invalidate();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
            int height) {

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {

    }

    /**
     * Draws current state of the game Canvas.
     */

    private int mBGFarMoveX = 0;
    private int mBGNearMoveX = 0;

    private void doDrawRunning(Canvas canvas) {

        // decrement the far background
        mBGFarMoveX = mBGFarMoveX - 1;

        // decrement the near background
        mBGNearMoveX = mBGNearMoveX - 4;

        // calculate the wrap factor for matching image draw
        int newFarX = backGround.getWidth() - (-mBGFarMoveX);

        // if we have scrolled all the way, reset to start
        if (newFarX <= 0) {
            mBGFarMoveX = 0;
            // only need one draw
            canvas.drawBitmap(backGround, mBGFarMoveX, 0, null);

        } else {
            // need to draw original and wrap
            canvas.drawBitmap(backGround, mBGFarMoveX, 0, null);
            canvas.drawBitmap(backGround, newFarX, 0, null);
        }

    }
}

现在我想要的是:
如果图像移动到达它的角落,它应该开始向另一侧移动。

我想要的是: see this video

我想要执行同样的事情。

1 个答案:

答案 0 :(得分:0)

一个非常简短的解决方案可能是通过以下方式替换课程的底部:

    /**
     * Draws current state of the game Canvas.
     */

    private int x = 0;
    private int ix = -1;

    private void doDrawRunning(Canvas canvas) {

        canvas.drawBitmap(backGround, -x, 0, null);

        if (x == 0 || backGround.getWidth() - x == getWidth())
            ix = -ix;

        x += ix;
    }
}

注意:此代码假定背景图片大于画布。