android游戏开发5-5 实现背景图的沿x轴移动

package com.mz.demo;

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

public class MySurfaceView extends SurfaceView implements Callback, Runnable {
    // 1.声明变量、对象
    private Paint paint;
    private Canvas canvas;
    private SurfaceHolder sfh;
    private Bitmap map1, map2;
    private int x = 0;
    private int y = 0;
    private int x2 = 0;
    private boolean isDo = true;
    private Thread thread;
    public MySurfaceView(Context context) {
        super(context);
        paint = new Paint();
        paint.setAntiAlias(true);
        sfh = this.getHolder();
        sfh.addCallback(this);
        map1 = BitmapFactory.decodeResource(getResources(),
                R.drawable.background);
        map2 = BitmapFactory.decodeResource(getResources(), R.drawable.water);
        // TODO Auto-generated constructor stub
    }

    public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
        // TODO Auto-generated method stub

    }

    public void surfaceCreated(SurfaceHolder holder) {
        // TODO Auto-generated method stub
        x = this.getWidth() - map2.getWidth();// 注1
        y = this.getHeight() - map2.getHeight();
        x2 = x - map2.getWidth();
        // Mydraw();
        thread = new Thread(this);//***这里要注意因为采用的是继承接口的方式,所以要在括号里些写this 总感觉期末可能作为改错题
        thread.start();
    }

    private void Mydraw() {
        // TODO Auto-generated method stub
        canvas = sfh.lockCanvas();//锁定画布
        canvas.drawColor(Color.WHITE);
        canvas.drawBitmap(map2, x, y, paint);
        canvas.drawBitmap(map2, x2, y, paint);
        sfh.unlockCanvasAndPost(canvas);//解锁
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        // TODO Auto-generated method stub

    }

    public void run() {
        // TODO Auto-generated method stub
        while (isDo) {
            Mydraw();
            logic();
            try {
                Thread.sleep(100);
            } catch (Exception e) {
                e.printStackTrace();
                // TODO: handle exception
            }

        }
    }

    private void logic() {
        // TODO Auto-generated method stub
        if(x>=this.getWidth()){
            x=this.getWidth() - map2.getWidth()-map2.getWidth()+1;//+1的作用是去点两个图pain连接处的间隙
        }else{
            x+=5;
        }
        if(x2>=this.getWidth()){
            x2=this.getWidth() - map2.getWidth()-map2.getWidth()+1;
        }else{
            x2+=5;
        }

    }

}

注释1:
android游戏开发5-5 实现背景图的沿x轴移动_第1张图片

你可能感兴趣的:(android)