2013-06-26 31 views
5

我打算做的是讓我的Android應用程序的用戶選擇臉上的點並從該觸摸中檢索X和Y座標。請看下面的圖片。從選擇中檢索中心點XY座標

Coordinates from face

我想用戶能夠改變選擇方形的大小。

到目前爲止,我有下面的代碼,但我真的不知道該從哪裏去。我如何去繪製一個用戶可以操縱和移動的矩形(然後從中返回X和Y中心點座標)? I'm sure there's an Android feature for this.

private void selectImg(){ 
    //retrieve X and Y values from touch 
    surfaceView.setOnTouchListener(new View.OnTouchListener() { 
     @Override 
     public boolean onTouch(View view, MotionEvent pos) { 
      //retrieve position when user finishes touch 
      if (pos.getAction() == MotionEvent.ACTION_UP){ 
        Log.d("X",String.valueOf(pos.getX())); 
        Log.d("Y",String.valueOf(pos.getY())); 
      } 
      return true; 
     } 
    });  
} 

謝謝!

可能是有用的: Custom Android Image Crop https://github.com/dtitov/pickncrop/blob/master/src/com/github/pickncrop/MainActivity.java

+0

您可以發佈結果的形象,如果我有這樣的形象是選擇的黃色矩形大,然後又是怎樣的結果會是什麼樣子? – KOTIOS

回答

1

那麼如果我理解正確,根據你的代碼中使用的是SurfaceView所以它裏面畫出你可以閱讀接受的答案here其中內private void drawMyStuff(final Canvas canvas)你必須把代碼畫出你想要的矩形,並每次更改某些內容(如座標)時,請致電invalidate()重新繪製SurfaceView

您也可以創建自己的自定義View並在其中繪製,您可以在我的項目here中看到我正在使用的工作示例。

您已經擁有觸摸的(x,y)座標,以便使用CanvasSurfaceView內繪製矩形。這裏是一些代碼,你可以借鑑,所有你需要做的就是用(X,Y)更改數字座標,你想畫:

Paint paint = new Paint(); 
paint.setColor(Color.BLACK); 
paint.setStrokeWidth(3); 
canvas.drawRect(30, 30, 80, 80, paint); 
paint.setStrokeWidth(0); 
paint.setColor(Color.CYAN); 
canvas.drawRect(33, 60, 77, 77, paint); 
paint.setColor(Color.YELLOW); 
canvas.drawRect(33, 33, 77, 60, paint); 

現在調整您的矩形,你將不得不拯救座標在某處,您可以使用Rect來保存每個矩形的座標。然後重新調整它們的大小,你可以讀取觸摸屏上的座標,看看它們是否在你的矩形座標的附近。我說近,因爲它很難精確地觸及拐角的座標,所以你必須看看它是否在例如拐角處的±10像素內。照顧矩形的大小,也許這10個像素是矩形的寬度或高度。

終於在ACTION_DOWN您跟蹤角落,我寫之前和ACTION_UP你把你ACTION_DOWN之前檢測的角的新座標,那麼,你叫invalidate()重繪的矩形和你做!

我希望你明白我的意思,並幫助你以某種方式:)

4

我不知道你有多少應用程序的完成。但是,您需要一種方法來識別移動正方形與拉伸正方形。你可以通過按鈕做到這一點,或者你可以在設計中做到這一點(從正方形內部移動並從邊界伸展)。

@Override 
    public boolean onTouch(View view, MotionEvent pos) { 
     //retrieve position when user finishes touch 
     if (pos.getAction() == MotionEvent.ACTION_UP){ 
       Log.d("X",String.valueOf(pos.getX())); 
       Log.d("Y",String.valueOf(pos.getY())); 
     } 
     //pseudo code 
     //if user is dragging 
      //get new dragged position 
      //if boundaries are being dragged 
       //redraw square to match new dragged position (requires some math to stretch properly) 
      //else if inside boundaries being dragged 
       //redraw the square to new dragged position (center it) 

     return true; 
    } 

您需要查看如何重繪正方形的示例。我不確定你是如何繪製它們的。

編輯:這裏有一些有用的來源。如果將二者結合起來,你應該能夠輕鬆地達到自己的目標:

Moving image with touch events

Android: How to stretch an image to the screen width while maintaining aspect ratio?

2

既然你已經得到觸摸點的所有你能做的就是畫一個矩形或正方形各地它與默認大小

Point touchPoint=new Point(x, y); 
Paint paint = new Paint(); 
paint.setColor(Color.parseColor("#00CCFF")); 
canvas.drawRect(x, y, x+100, y+100, paint); 

然後根據矩形中的觸摸點,您可以拖動或縮放矩形。
有一個谷歌教程,你可以使用拖動和縮放矩形。
在下面找到鏈接。
http://developer.android.com/training/gestures/scale.html