使用surfaceview android从左到右移动图像

时间:2015-01-06 02:30:56

标签: android

我试图理解使用surfaceview。我希望图像使用surfaceview从左向右移动。目前正在绘制图像,但我无法移动。我应该在哪里调用变量x1和y1。另外我怎么能调用invalidate()方法,我想让图像从左到右反复移动。感谢

public class GameBoardTwo extends SurfaceView {

private Bitmap bitmap1;

private SurfaceHolder holder;
int x1, y1;



public GameBoardTwo(Context context) {

    super(context);

    holder = getHolder();
    bitmap1 = BitmapFactory.decodeResource(getResources(), R.drawable.blueball);
    init();

    holder.addCallback(new SurfaceHolder.Callback() {

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {

        }

        @Override
        public void surfaceCreated(SurfaceHolder holder) {

            Canvas c = holder.lockCanvas(null);

            drawSomething(c);

            holder.unlockCanvasAndPost(c);

        }



        @Override
        public void surfaceChanged(SurfaceHolder holder, int format,

                                   int width, int height) {

        }

    });



}

   private void init(){

      x1 = 0;

       y1 = 100;


}



protected void drawSomething(Canvas canvas) {


   canvas.drawColor(Color.WHITE);



 if(x1 < canvas.getWidth()){

     x1 += 5;
 }

 else{
     x1 = 0;
 }

  canvas.drawBitmap(bitmap1, x1, y1, null);


}

}

1 个答案:

答案 0 :(得分:0)

您需要使用thread / runnable接口并覆盖run()。像这样:

@Override
protected void run(){
    while(true){
         drawSomething(c);//c is your locked canvas
         try{
             Thread.sleep(50)
         } catch(Exception e){}

    }

}