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; 
    } 
     

  
 
 

摘自 落日小屋

發佈留言