2013-04-04 43 views
2

我有一個使用drawRect(Rect,Paint)繪製的Rect對象。我有一個OnTouchEvent來檢查觸摸位置是否在Rect內。如果觸摸位於Rect內部,屏幕上的某些內容會發生變化。 我遇到的問題是:我必須觸摸的位置才能使觸摸語句執行的距離比Rect對象高出50個像素。OnTouchEvent不確定drawRect的位置是

這裏是我的代碼的相關部分:

public class MainActivity extends Activity { 
    DrawView drawView; 
    RelativeLayout fLY; 
    static Rect newGame = new Rect(LEFT, 165 + 35, 320, 200 + 35); 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); 
     fLY = new RelativeLayout(this); 
     drawView = new DrawView(this); 
     fLY.addView(drawView); 
     setContentView(fLY); 
    } 

    @Override 
    public boolean onTouchEvent(MotionEvent event) { 
     int touchX = (int)event.getX(); 
     int touchY = (int)event.getY(); 
     switch(event.getAction()){ 
      case MotionEvent.ACTION_DOWN: 
      if(newGame.contains(touchX, touchY))reset(); 
     } 
    } 

而且我drawView函數類:

public class DrawView extends View{ 
    Paint paint = new Paint(); 
    int COLORS[] = Constants.COLORS; 
    int left = 250; 
    int size = 35; 

    public DrawView(Context context) { 
     super(context); 
    } 

    @Override 
    public void onDraw(Canvas canvas) { 
     canvas.drawRect(MainActivity.newGame, paint); 
    } 
} 

回答

0

這可能是關閉的狀態欄的確切高度。你可以通過這個答案得到狀態欄的高度:Height of statusbar?

然後加入到你的getY它應該工作。

+0

狀態欄和/或標題欄的高度是問題。但是當我在鏈接中運行代碼時,它說狀態和標題欄高度等於零,所以我無法通過抵消yPos來解決我的問題。我把代碼放在了我的onCreate方法的末尾。我通過完全刪除標題和狀態欄來暫時解決了我的問題。 – 2013-04-04 05:25:25