您好我在画布上绘制了一个位图,当用户触摸它时我想做点什么。
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()
做错了。有人可以帮帮我吗?
答案 0 :(得分:1)
首先在画布上获取位图的矩形。然后在onTouchEvent
中,检查触摸的x,y包含在之前的矩形中。
添加了示例:
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.
}
}