我有一个名为ChickenView的Surfaceview类,我试图让我的bMapEgg有一个touchevent。我尝试使用此bMapEgg.setOnTouchListener(this);
但它没有用。有什么想法吗?
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);
}
}
答案 0 :(得分:0)
首先,您需要为整个SurfaceView设置触控侦听器。接下来,要检查位图是否被触摸,您需要执行以下操作:
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;
}
}