图像未显示在“onTouch”方法中

时间:2014-04-11 11:51:24

标签: android android-canvas android-view surfaceview

我想举例说明用户触摸屏幕时应显示可绘制的图像。

我使用过画布,但屏幕始终显示为空白。以下是我的代码:

    public class MainActivity extends Activity implements OnTouchListener {

    MySurfaceView mySurfaceView;
    float x, y;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mySurfaceView = new MySurfaceView(MainActivity.this);
        mySurfaceView.setOnTouchListener(this);
        x = 0;
        y = 0;
        setContentView(mySurfaceView);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        // TODO Auto-generated method stub
        x = event.getX();
        y = event.getY();
        return false;
    }

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

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

    class MySurfaceView extends SurfaceView implements Runnable {

        SurfaceHolder mSurfaceHolder;
        Thread mThread;
        boolean isRunning = true;

        public MySurfaceView(Context context) {
            super(context);
            mSurfaceHolder = getHolder();
        }

        @Override
        public void run() {
            while (isRunning) {
                if (!mSurfaceHolder.getSurface().isValid()) {
                    continue;
                }
                Canvas canvas = mSurfaceHolder.lockCanvas();
                canvas.drawRGB(02, 02, 150);
                if (x != 0 || y != 0) {
                    Bitmap test = BitmapFactory.decodeResource(getResources(),
                            R.drawable.ic_launcher);
                    canvas.drawBitmap(test, x, y, null);
                }
                mSurfaceHolder.unlockCanvasAndPost(canvas);
            }
        }

        public void pause() {
            isRunning = false;
            while (true) {
                try {
                    mThread.join();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            }
            mThread = null;
        }

        public void resume() {
            isRunning = true;
            mThread = new Thread();
            mThread.start();
        }

    }

}

1 个答案:

答案 0 :(得分:1)

将runnable添加到mThread。

public void resume() {
        isRunning = true;
        mThread = new Thread(this);
        mThread.start();
    }