安卓atan2函数可以直接返回点(x,y)的弧度,* 180 / Math.PI 得到角度°.
Math.atan2(x,y)
如下代码计算弧形点击区域对应的值,
channelLabel = (ImageView)(findViewById(R.id.walkie_label));
channelLabel.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if(motionEvent.getAction() == MotionEvent.ACTION_DOWN){
double x = motionEvent.getX() - 482;
double y = 476 - motionEvent.getY();
double distance = Math.sqrt(x * x + y * y);
if(distance > 345 && distance < 485){
double angle = Math.atan2(x,y) * 180 / Math.PI + 90;
int pos = 0;
for (;angle > channelAngle[pos];++pos) {
;
}
++pos;
if(angle < 0 || angle > 180) {
pos = 0;
}
curChannel = pos;
Log.e(TAG,String.valueOf(curChannel));
if (mSerialPortUtil != null) {
cmdChannel[5] = (byte)(pos);
if(!mSerialPortUtil.sendCmds(cmdChannel)){
curChannel = 0;
}
}
mHandler.sendMessage(mHandler.obtainMessage(MSG_UPDATE_CHANNEL));
}
}
return false;
}
});
点击的控件是如下图的ImageView,需要得到点击的1-16值: