package com.example.my_touch3;
import ...
public class MainActivity extends Activity {
private int x,y;//圓心
private int gRadius=100;//預設圓半徑
private int touchx1,touchy1,touchx2,touchy2;//用來判斷當兩點觸控圓心所用
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new TouchView(this));
// 取得螢幕解析度,dm.widthPixels為寬,dm.heightPixels為高
DisplayMetrics dm = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(dm);
x = (dm.widthPixels)/2;
y = (dm.heightPixels)/2;
}
//自建的類別,繼承View,當成活動之畫面呈現
private class TouchView extends View{
private Paint paint;
//類別建構式
public TouchView(Context context) {
super(context);
paint=new Paint();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//設定畫筆顏色,反鋸齒,挖空心
paint.setColor(0xffff0000);
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE);
//畫圓 (圓心X,圓心Y,半徑,畫筆)
canvas.drawCircle(x, y, gRadius, paint);
}
//螢幕觸控事件處理,這邊是簡易方法只能偵測layout,無法針對特定元件進行監聽
@Override
public boolean onTouchEvent(MotionEvent event) {
int pointerNum=event.getPointerCount();
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
break;
case MotionEvent.ACTION_MOVE:
if(pointerNum==1){
//單點觸控時
x=(int) event.getX();
y=(int) event.getY();
}else if(pointerNum==2){
//兩點觸控時
touchx1=(int)event.getX(0);
touchy1=(int)event.getY(0);
touchx2=(int)event.getX(1);
touchy2=(int)event.getY(1);
x=(int)(touchx1+touchx2)/2;
y=(int)(touchy1+touchy2)/2;
//取得圓半徑的公式
gRadius=(int)(Math.sqrt( (Math.pow(touchx1-touchx2,2))+ (Math.pow(touchy1-
touchy2,2))));
}
invalidate();//自動呼叫onDraw方法
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
}
}
沒有留言:
張貼留言