简体   繁体   中英

Surfaceview with bitmap touchevent

I have a Surfaceview Class called ChickenView and I'm trying to make my bMapEgg have a touchevent. I tried using this bMapEgg.setOnTouchListener(this); but it didn't work. Any ideas?

public void drawCourt()  {

            if (ourHolder.getSurface().isValid()) {
                canvas = ourHolder.lockCanvas();
                //Paint paint = new Paint();
                canvas.drawColor(Color.BLACK);//the background
                paint.setColor(Color.argb(255, 255, 255, 255));
                paint.setTextSize(45);
                canvas.drawText("Score:" + score + " Lives:" + lives + " fps:" + fps, 20, 40, paint);

                Bitmap bMapEgg = BitmapFactory.decodeResource(getResources(), R.drawable.egg);
                bMapEgg = scaleDown(bMapEgg,180,true);

                Bitmap bMapBackground = BitmapFactory.decodeResource(getResources(), R.drawable.backgrounddd);
                canvas.drawBitmap(bMapBackground, 0, 0, paint);
                canvas.drawBitmap(bMapEgg, ballPosition.x, ballPosition.y, paint);



                ourHolder.unlockCanvasAndPost(canvas);
            }

        }

First, you need to setup a touch listener for the whole SurfaceView. Next, to check whether the bitmap was touched you need to do something like this:

float x = touchEvent.getX();
float y = touchEvent.gety();
// Replace these with the correct values (bitmap x, y, width & height)
float x1 = bitmapPositionX;
float x2 = x1 + bitmapWidth;
float y1 = bitmapPositionY;
float y2 = y1 + bitmapHeight;
// Test to see if touch is inside the bitmap
if (x > x1 && x < x2 && y > y1 && y < y2) {
    // Bitmap was touched
    switch (touchEvent.getAction()) {
    case TouchEvent.ACTION_DOWN: (bitmap was just touched) break;
    case TouchEvent.ACTION_DOWN: (user lifted finger from bitmap) break;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM