我先说说我自己的思路,也希望大家能告诉我更好得实现方式
思路:把一张图切成好几张图片,然后叠加绘制在一起,然后判断点击后产生得坐标,是否在所点击图片区域之类,然后判断是否点击得是透明区域,如果是透明就,传递到下层图片,如果不是直接显示内容.
代码如下:
import java.util.HashMap;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.view.MotionEvent;
import android.view.View;
/**
* @author HuangYunLin
*
*/
public class RectsView extends View {
private Bitmap[] mBitmaps;
private Bitmap bitmap1, bitmap2, bitmap3, bitmap4;
private Rect mRect[];
private HashMap<Rect, Bitmap> cacheBitMap;
private Rect mRect1;
private Rect rect;
private float x, y;
private Paint mPaint;
private boolean isOnTouch;
public RectsView(Context context) {
super(context);
cacheBitMap = new HashMap<Rect, Bitmap>();
//抠图,每张图片得宽高都一样
bitmap1 = ((BitmapDrawable) getResources().getDrawable(R.drawable.head)).getBitmap();
bitmap2 = ((BitmapDrawable) getResources().getDrawable(R.drawable.close)).getBitmap();
bitmap3 = ((BitmapDrawable) getResources().getDrawable(R.drawable.boots)).getBitmap();
bitmap4 = ((BitmapDrawable) getResources().getDrawable(R.drawable.bag)).getBitmap();
mBitmaps = new Bitmap[4];
mBitmaps[0] = bitmap1;
mBitmaps[1] = bitmap2;
mBitmaps[2] = bitmap3;
mBitmaps[3] = bitmap4;
mRect = new Rect[4];
mPaint = new Paint();
mPaint.setColor(Color.RED);
// 创建和位图一样位置的Rect
for (int i = 0; i < mRect.length; i++) {
mRect[i] = new Rect(0, 0, bitmap1.getWidth(), bitmap1.getHeight());
cacheBitMap.put(mRect[i], mBitmaps[i]);
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
for (int i = 0; i < mBitmaps.length; i++) {
canvas.drawBitmap(mBitmaps[i], 0, 0, mPaint);
}
if (isOnTouch) {
isOnTouch = false;
System.out.println("点击X:" + x + "点击Y:" + y);
for (int i = 0; i < mRect.length; i++) {
//判断点击得坐标点是否在图片范围内
if (mRect[i].contains((int) x, (int) y)) {
//判断坐标点不超过图片得宽高
if ((int) x > bitmap1.getWidth() || (int) y > bitmap1.getHeight()) {
return;
}
Bitmap mBitmap = cacheBitMap.get(mRect[i]);
System.out.println("范围之内:" + i);
//判断坐标点是否是在图片得透明区域
if (mBitmap.getPixel((int) x, (int) y) == 0) {
System.out.println("bitmap透明区域:" + i);
// second(canvas);
} else {
System.out.println("不透明区域:" + i);
mPaint.setColor(Color.RED);
mPaint.setTextSize(15);
canvas.drawLine(x, y, x + 30, y, mPaint);
canvas.drawText("点击得是-->" + i, x + 30, y+5, mPaint);
break;
}
}
}
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
isOnTouch = true;
x = event.getX();
y = event.getY();
// 重绘
invalidate();
}
return true;
}
}