Android:SurfaceView / Canvas显示黑屏而不是绘制我的Bitmap

时间:2015-04-07 14:12:22

标签: android canvas android-studio bitmap surfaceview

我一直在尝试创建一个简单的游戏,其中一个位图(称为猎人)在屏幕上点击方向移动。我一直在关注本教程:https://www.youtube.com/watch?v=oLf32M6lUKo。它建议使用SurfaceView绘制Bitmap和OnTouchListener以帮助移动角色。

不幸的是,当我尝试运行代码时,模拟器只显示黑屏。

这是我的代码。

public class MoveTwo extends Activity implements View.OnTouchListener {

    Bitmap hunter;
    OurView v;
    float x, y;
    float newX, newY;
    Paint p;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        v = new OurView(this);
        v.setOnTouchListener(this);
        hunter = BitmapFactory.decodeResource(getResources(), R.drawable.hunter);
        x = y = 0;
        setContentView(v);
        this.p = new Paint();
        p.setColor(Color.WHITE);
    }

    public boolean onTouch(View v, MotionEvent me) {
        newX = me.getX();
        newY = me.getY();
        return true;
    }

    public class OurView extends SurfaceView implements Runnable {
        Thread t = null;
        boolean ok = false;
        SurfaceHolder holder;

        public OurView(Context context) {
            super(context);
            holder = getHolder();
        }

        public void run() {
            while (ok == true) {
                if (!holder.getSurface().isValid()) {
                    continue;
                }
                if (newY > y) {
                    y += 5;
                }
                if (newY < y) {
                    y -= 5;
                }
                if (newX > x) {
                    x +=5;
                }
                if (newX < x) {
                    x -= 5;
                }
                Canvas c = holder.lockCanvas();
                c.drawARGB(255, 150, 150, 10);
                c.drawBitmap(hunter, x, y, p);
                holder.unlockCanvasAndPost(c);
            }
        }

        public void pause() {
            ok = false;
            while (true) {
                try {
                    t.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                break;
            }
            t = null;
        }

        public void resume() {
            ok = true;
            t = new Thread(this);
            t.start();
        }
    }
}

你对我有什么建议吗?我不熟悉SurfaceView,所以我一直在努力找出API并自己找到解决方案。

谢谢!

1 个答案:

答案 0 :(得分:0)

尝试在onTouch方法之前添加此代码

  @Override
    protected void onPause() {
    super.onPause();
    v.pause();
}

@Override
protected void onResume() {
super.onResume();
v.resume();
}