首页 > 解决方案 > 为同一图像的不同部分设置点击侦听器

问题描述

我有一个看起来像这样的单一身体图像

在此处输入图像描述

我需要做的是区分点击身体的不同部位。例如,如果点击了头部,那么onHeadClicked应该执行一个函数。如果我点击左手,那么一个函数onLeftHandClicked。这将如何运作?

标签: androidandroid-layoutuser-interface

解决方案


首先,您必须将身体点的坐标存储在实际图像中。然后只需检查点击坐标是否在身体点的坐标内。您还应该确保使用图像视图的矩阵及其在屏幕上的坐标来缩放点

例如,如果

        class BodyPoint{
              String name;
              int x;
              int y;
              public(String name,int x,int y){
                   this.name = name;
                   this.x = x;
                   this.y = y;}
             }
        BodyPoint headCoordinates = new BodyPoint ("head",50,20);
        BodyPoint neckCoordinates = new BodyPoint ("neck",50,50);
        BodyPoint leftHandCoordinates = new BodyPoint ("leftHand",10,50);
        BodyPoint rightHandCoordinates = new BodyPoint ("rightHand",80,50);

        BodyPoint[] bodyCoordinates = new BodyPoint[]{headCoordinates,neckCoordinates,
        leftHandCoordinates ,rightHandCoordinates };

    yourImgView.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
             int[] viewCoords = new int[2];
                yourImgView.getLocationOnScreen(viewCoords);

    int touchX = (int) event.getX();
    int touchY = (int) event.getY();

    int imageX = touchX - viewCoords[0]; // viewCoords[0] is the X coordinate
    int imageY = touchY - viewCoords[1]; 
    Matrix mMatrix = getImageMatrix();
    float[] f = new float[9];
    mMatrix .getValues(f);

   float scaleX = f[Matrix.MSCALE_X];
   float scaleY = f[Matrix.MSCALE_Y];

    processTouchedPoints(imageX/(int)scaleX , imageY/(int)scaleY );
            return true;

        }
    });

    ...
    int range = 50;
    void processTouchedPoints(int imageX,int imageY){
      foreach(BodyPoint mBodyPoint:bodyCoordinates ){
    int x = mBodyPoint.x;
    int y = mBodyPoint.y;
          if((imageX> (x-range) && imageX<(x+range))
           &&(imageY> (y-range) && imageY<(y+range))){
           doWhatever(mBodyPoint.name)
         }
      }
    }

推荐阅读