Android 为onClick 事件将图像划分为多个区域

Android divide an image in multiple region for onClick events

在这个应用程序中,我有一个代表德国地图的图像。我希望能够点击一个特定的州,例如巴伐利亚,然后应该会发生一些事情(点击功能)。

我也许可以在填充白色空白图像的图像顶部放置一个 table 布局,并仅在覆盖各州的图像上激活单击方法,但这可能是错误的编码,我认为会与其他类型的设备兼容性较差,tablet 或 bigger/smaller 屏幕。

另一种解决方案是创建地图的两个图像。一个具有不同颜色的状态,另一个具有要显示的所需布局。将彩色的放在第二个上面。

XML :

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:id="@+id/my_frame"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     android:background="@color/background" >
 <ImageView 
     android:id="@+id/image_areas"
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:scaleType="fitCenter"
     android:visibility="invisible"
     android:src="@drawable/mapcolor" />

 <ImageView
     android:id="@+id/image"
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:scaleType="fitCenter"
     android:src="@drawable/mapdisplay"/>
</FrameLayout>

Java :

public boolean onTouch (View v, MotionEvent ev) {
     final int action = ev.getAction();
     // (1) 
     final int evX = (int) ev.getX();
     final int evY = (int) ev.getY();
     switch (action) {
     case MotionEvent.ACTION_DOWN :
       if (currentResource == R.drawable.mapdisplay) { 
       } 
       break;
     case MotionEvent.ACTION_UP :
       // Switch to a different image, depending on what color was touched.
       int touchColor = getHotspotColor (R.id.image_areas, evX, evY);
       // Switch to a different image, depending on what color was touched.
       ColorTool ct = new ColorTool ();
       int tolerance = 25;
       nextImage = R.drawable.mapdisplay;
       // (3)
       if (ct.closeMatch (Color.RED, touchColor, tolerance)) {
          // Do the action associated with the RED region
          // onClick function here ?
       } else {
         //...
       }
       break;
      } // end switch
      return true;
}

颜色工具:

public class ColorTool {
    public boolean closeMatch (int color1, int color2, int tolerance) {
        if ((int) Math.abs (Color.red (color1) - Color.red (color2)) > tolerance ) return false;
        if ((int) Math.abs (Color.green (color1) - Color.green (color2)) > tolerance ) return false;
        if ((int) Math.abs (Color.blue (color1) - Color.blue (color2)) > tolerance ) return false;
        return true;
    } // end match
} // end class

不出所料,这对我不起作用。有人可以向我解释一下这种方法或一种让图像 "map" 具有多个区域可供点击的好方法吗?

我正在考虑拥有一个包含各州地图的二维矩阵。应该有一个矩阵的初始版本,它根据它们的位置为不同的区域映射不同的数字。对于更大或更小的屏幕尺寸,矩阵需要是动态的并在像素之间重新映射。让我们以下面的网格为例。

--------------
00111122224444
01111222222444
11122222444444
11222244444433
12222444444333
22224444444433
22255444444333
22555554443333
25555555433333
--------------

我们可以在这里看到 5 个州,它们在地图后面的矩阵中分别编号。如果屏幕尺寸加倍,则需要将值转换为更大的段,反之亦然。

我正在考虑绘制这样的矩阵,它可以根据屏幕尺寸转换成更大或更小的尺寸。现在需要将地图的图像设置为屏幕背景,并取onTouchListener获取触摸区域的像素,以确定被点击的区域。

这只是为了说明如何解决这个问题。我发现了一个类似的想法 here in the MapChart。希望有帮助!