Android 多點觸控 (Multi-Touch)


Android 的多點觸控 (multi-touch),

onTouchEvent 事件中, 可透過 MotionEvent 實現之,

範例, 如下 :

Java 程式 :
 程式碼
public class helloWorld extends Activity
{
private int gCenterX = 160;
private int gCenterY = 240;
private int gRadius = 100;

private int gTouchX1, gTouchY1, gTouchX2, gTouchY2;

/** Called when the activity is first created. */
@Override

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView( new View(this){

Paint vPaint = new Paint(); // 繪製樣式物件
private int i = 0; // 弧形角度

@Override
protected void onDraw(Canvas canvas)
{
// TODO Auto-generated method stub
super.onDraw(canvas);

// 設定繪圖樣式
vPaint.setColor( 0xff00ffff ); // 畫筆顏色
vPaint.setAntiAlias( true ); // 反鋸齒
vPaint.setStyle( Paint.Style.STROKE );

// 繪製一個圓形
canvas.drawCircle( gCenterX, gCenterY, gRadius, vPaint );
}

@Override
public boolean onTouchEvent(MotionEvent event)
{
int pointerCount = event.getPointerCount(); // 幾個觸控點

switch( event.getAction() )
{
case MotionEvent.ACTION_DOWN: // 按下
break;

case MotionEvent.ACTION_MOVE: // 拖曳移動

if( pointerCount == 1 ) // 單點觸控
{
gCenterX = (int) event.getX();
gCenterY = (int) event.getY();
}
else if( pointerCount == 2 ) // 多點觸控
{
gTouchX1 = (int) event.getX(0); // 第一個觸控點
gTouchY1 = (int) event.getY(0);
gTouchX2 = (int) event.getX(1); // 第二個觸控點
gTouchY2 = (int) event.getY(1);

gCenterX = (int)((gTouchX1 + gTouchX2)/2);
gCenterY = (int)((gTouchY1 + gTouchY2)/2);
gRadius = (int)(Math.sqrt( Math.pow(gTouchX2-gTouchX1, 2)
+ Math.pow(gTouchY2-gTouchY1, 2)
)/2);
}

// 重繪, 再一次執行 onDraw 程序
invalidate();
break;

case MotionEvent.ACTION_UP: // 放開
break;
}

// TODO Auto-generated method stub
return true;
}
});
}
}

範例結果 :




Related Posts Plugin for WordPress, Blogger...