2013-08-06 6 views
-1

Я работаю над Android-приложением Compass, где у меня будет изображение компаса с буквами, указывающими разные направления («N» для «Север», «E» для Востока и т. Д. на). Пользователь мог нажать любую букву и получить информацию о заданном направлении. Я ищу способ привязки сенсорных координат к изображению, т. Е. Если пользователь нажимает букву «N», они всегда будут получать одинаковые координаты, не имеющие отношения к тому, с которым обращается телефон. Ниже приведен код, который я использую сейчас.Как привязать координаты касания к изображению

@Override 
    public View onCreateView(LayoutInflater inflater, 
          ViewGroup container, 
          Bundle savedInstanceState) { 
    View v=inflater.inflate(R.layout.compass_fragment, container, false); 

    compassView = (CompassView) v.findViewById(R.id.compass_view); 



    compassView.setOnTouchListener(new OnTouchListener() { 
     @Override 
     public boolean onTouch(View view, MotionEvent motion) { 

      Log.i(TAG, "In onTouch"); 

      // Get the action that was done on this touch event 
      switch (motion.getAction()) 
      { 

       case MotionEvent.ACTION_DOWN: 
       { 
        return true; 
       } 

       case MotionEvent.ACTION_UP: 
       { 
        float x = motion.getX(); 
        float y = motion.getY(); 

        Log.i(TAG, "ACTION UP x = " + x + " y = " + y); 
        break; 
       } 
      } 
      // if you return false, these actions will not be recorded 
      return true; 
     } 
    }); 


    mSensorManager = (SensorManager)getActivity().getSystemService(Context.SENSOR_SERVICE); 
    accelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); 
    magnetometer = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); 

    return(v); 
    } 
+0

Знаете ли вы, как вращать изображение, и вы не знаете, как связать его с прикосновением? – Gina

+0

Джина, нет, я не знаю, думаю, иначе я бы не стал задавать вопрос. Я новичок в Android, все еще изучая, как все работает вместе. Похоже, для вас очевидно, как это сделать, я был бы признателен за то, что вы получили от вас некоторые указания. Спасибо. – ITango

+0

Затем выясните, как повернуть изображение. Для «N» или «E» сделайте его объектом, таким как Button/ImageButton, чтобы вам не нужно было знать координаты. – Gina

ответ

0

Я отработал ответ на свой вопрос. Он работает так, как я хотел, без использования кнопок. Я прикрепил код ниже, надеюсь, что это может быть полезно для кого-то другого.

Чтобы получить касание направления на компасе, я вычисляю угол смещения между текущим знаком компаса (градусная переменная, которая обновляется методом setDegrees, вызванным из другого класса) и углом касания по отношению к оси Y.

public class CompassView extends ImageView { 
    private float degrees=0; 
    private String touchDirection; 

    public CompassView(Context context, AttributeSet attrs) { 
     super(context, attrs); 
    } 

    @Override 
    protected void onDraw(Canvas canvas) { 
     int height = this.getHeight(); 
     int width = this.getWidth(); 

     canvas.rotate(360-degrees, width/2, height/2); 
     super.onDraw(canvas); 
    } 

    public void setDegrees(float degrees) { 
     this.degrees = degrees; 
     this.invalidate(); 
    } 

    @Override 
     public boolean onTouchEvent(MotionEvent event) { 

     switch (event.getAction()) { 
      case MotionEvent.ACTION_DOWN: 
       return true; 
      case MotionEvent.ACTION_MOVE: 
       break; 
      case MotionEvent.ACTION_UP: 
       float eventX = event.getX(); 
       float eventY = event.getY(); 

       touchDirection = getTouchDirection(eventX, eventY); 

       Context context = getContext(); 
       Intent intent = new Intent(context, CompassDirectionInfo.class); 
       Bundle bundle = new Bundle(); 
       bundle.putString("DIRECTION", touchDirection); 
       intent.putExtras(bundle); 
       context.startActivity(intent); 
       break; 
      default: 
       return false; 
     } 
     return true; 
     } 

    private String getTouchDirection (float eventX, float eventY) { 

     String direction = ""; 

     float centreX = getWidth()/2, centreY = getHeight()/2; 
     float tx = (float) (eventX - centreX), ty = (float) (eventY - centreY); 
     float radius = (float) Math.sqrt(tx*tx + ty*ty); 

     float offsetX = 0, offsetY = radius, adjEventX = eventX - centreX, adjEventY = centreY - eventY; 

     double cosaU = ((offsetX * adjEventX) + (offsetY * adjEventY)); 
     double cosaD = (Math.sqrt((offsetX * offsetX) + (offsetY * offsetY)) * Math.sqrt((adjEventX * adjEventX) + (adjEventY * adjEventY))); 
     double cosa = cosaU/cosaD; 

     double degr = (Math.acos(cosa) * (180/Math.PI)); 

     if (adjEventX < 0) 
      degr = 360 - degr; 

     float offsetDegrees = (float) (degrees + degr); 

     if (offsetDegrees > 360) 
      offsetDegrees = offsetDegrees - 360; 

     if (offsetDegrees < 22.5 || offsetDegrees > 336.5) 
      direction = "NORTH"; 
     else if (offsetDegrees > 22.5 && offsetDegrees < 67.5) 
      direction = "NORTHEAST"; 
     else if (offsetDegrees > 67.5 && offsetDegrees < 112.5) 
      direction = "EAST"; 
     else if (offsetDegrees > 112.5 && offsetDegrees < 156.5) 
      direction = "SOUTHEAST"; 
     else if (offsetDegrees > 156.5 && offsetDegrees < 201.5) 
      direction = "SOUTH"; 
     else if (offsetDegrees > 201.5 && offsetDegrees < 246.5) 
      direction = "SOUTHWEST"; 
     else if (offsetDegrees > 246.5 && offsetDegrees < 291.5) 
      direction = "WEST"; 
     else if (offsetDegrees > 291.5 && offsetDegrees < 336.5) 
      direction = "NORTHWEST"; 

     return direction; 
    } 
} 
Смежные вопросы