0

嗨,我在画布上画了一张位图,当用户触摸它时我想做点什么。

Bitmap backbutton = BitmapFactory.decodeResource(getResources(),
            R.drawable.backbutton);
    Paint paint = new Paint();

canvas.drawBitmap(backbutton, canvasWidth - 100, 0, paint);

我尝试了以下方法来解决问题,但它不起作用。如何正确检查入站?

public void onTouch(View view, MotionEvent event) {
    if(backbutton.contains((int) (event.getX()), (int)(event.getY()), (int)(event.getX()+100),(int) (event.getY()+30))) {
        Toast.makeText(view.getContext(), "this works", Toast.LENGTH_LONG).show();

    }

}

但我似乎对contains(). 有人可以帮我吗?

4

1 回答 1

1

首先在画布上获取位图的矩形。然后在onTouchEvent,检查触摸的x,y是否包含在rect之前。

添加示例:

public class MyView extends View {
Rect bitmapRect;
public MyView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}

public MyView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);    //To change body of overridden methods use File | Settings | File Templates.

    Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);

    Rect source = new Rect(0,0,bitmap.getWidth(), bitmap.getHeight());
    bitmapRect = new Rect(0,0, bitmap.getWidth(), bitmap.getHeight());

    canvas.drawBitmap(bitmap, source, bitmapRect, new Paint());

}

@Override
public boolean onTouchEvent(MotionEvent event) {
    int x = (int)event.getX();
    int y =   (int)event.getY();
    if(null != bitmapRect && bitmapRect.contains(x,y)){
        Toast.makeText(view.getContext(), "this works", Toast.LENGTH_LONG).show();
    }


    return super.onTouchEvent(event);    //To change body of overridden methods use File | Settings | File Templates.
}

}

于 2013-09-12T14:44:21.553 回答