Android开发经验之点击图片判断是否在图片范围之内
- package xiaosi.grivaty;
- import android.content.Context;
- import android.graphics.Bitmap;
- import android.graphics.BitmapFactory;
- import android.graphics.Canvas;
- import android.graphics.Rect;
- import android.view.MotionEvent;
- import android.view.View;
- public class Rects extends View
- {
- private Bitmap bitmap = null;
- private float x,y;
- public Rects(Context context)
- {
- super(context);
- }
- @Override
- protected void onDraw(Canvas canvas)
- {
- super.onDraw(canvas);
- bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.v);
- canvas.drawBitmap(bitmap, 0, 0, null);
- //创建和位图一样位置的Rect
- Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
- if(rect.contains((int)x, (int)y)){
- System.out.println("范围之内");
- }
- else{
- System.out.println("范围之外");
- }
- System.out.println("图片宽度:" + bitmap.getWidth() + "图像高度:" + bitmap.getHeight());
- System.out.println("点击X:" + x + "点击Y:" + y);
- }
- @Override
- public boolean onTouchEvent(MotionEvent event)
- {
- if (event.getAction() == MotionEvent.ACTION_DOWN)
- {
- x = event.getX();
- y = event.getY();
- // 重绘
- invalidate();
- }
- return true;
- }
- }