首先要把图片处理好,要求每张图片大小一致,没有内容的地方就用透明填充,这个可以请UI设计师搞定。我们拿到图片把它们层叠着放在一起。
1. 布局
<RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="centerCrop" android:src="@drawable/bg_home" /> <ImageView android:id="@+id/kjsc" android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="centerCrop" android:src="@drawable/kjsc" /> <ImageView android:id="@+id/sd" android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="centerCrop" android:src="@drawable/sd" /> <ImageView android:id="@+id/ptjzsg" android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="centerCrop" android:src="@drawable/ptjzsg" /> <ImageView android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="centerCrop" android:src="@drawable/ck" /> <ImageView android:id="@+id/nzgf" android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="centerCrop" android:src="@drawable/nzgc" /> <ImageView android:id="@+id/pty" android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="centerCrop" android:src="@drawable/pty" /> </RelativeLayout>
布局大概像这样,bg_home是背景图,其他几张是上面的图标。使用android:scaleType="centerCrop"属性可以让图片在不失真的情况下自适应的充满屏幕。只要在图片的四周留上足够的非交互区域,可以花最小的工作量满足一般手机的屏幕适配。
2. 代码
@Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: Bitmap bitmap = getBitMap(v.getId()); int x = (int) event.getX(); int y = (int) event.getY(); if (bitmap != null && x < bitmap.getWidth() && y < bitmap.getHeight()) { int pixel = bitmap.getPixel(x, y); if (pixel != 0) { callBuildingMethod(v.getId()); return true; } } break; } return false; }
private Bitmap getBitMap(int id) { switch (id) { case R.id.kjsc: return bitmapKJSC; case R.id.sd: return bitmapSD; case R.id.ptjzsg: return bitmapPTJZSG; case R.id.nzgf: return bitmapNZGF; case R.id.pty: return bitmapPTY; } return null; }
在代码实现比较简单,处理点击事件即可,我们可以在界面的onTouch方法里,拦截ACTION_DOWN点击事件处理。
bitmap有一个getPixel(x, y)方法,通过传入点击时的x、y坐标来判断当前位置是否有像素点,如果获取到的像素点!=0说明这边有图片不是透明的,反之则没有图片。调用方法前需要判断x < bitmap.getWidth() && y < bitmap.getHeight(),这个是确保被判断的坐标点确实在bitmap里面,如果不在里面可能会报错。有像素点我们就可以通过调取自己定义的callBuildingMethod(v.getId())方法根据传入的view处理这个点击事件,完了返回true消费掉这个点击事件。如果什么都没有,或者是其他的点击事件,我们就需要return false把这个点击事件传递给下方的View来处理这个点击事件。
bitmap对象可以在页面初始化时通过ImageView的getDrawable()方法获取。
bitmapKJSC = ((BitmapDrawable) (binding.kjsc.getDrawable())).getBitmap(); bitmapSD = ((BitmapDrawable) (binding.sd.getDrawable())).getBitmap(); bitmapPTJZSG = ((BitmapDrawable) (binding.ptjzsg.getDrawable())).getBitmap(); bitmapNZGF = ((BitmapDrawable) (binding.nzgf.getDrawable())).getBitmap(); bitmapPTY = ((BitmapDrawable) (binding.pty.getDrawable())).getBitmap();
3. 效果
第一张图是背景,中间几张是图标,最后一张是图片合成后的效果,点击每个图标后会执行不同的方法,基本满足需求。