@Kedar Tendolkar
提供了一个很好的解决方案参考
基于 PNG 图像的选择...检测 onTouch 图像上的 非透明 颜色。
因此,如果您有一个具有透明背景的 PNG 图像,它将帮助您根据自己的图像检测触摸活动,如果颜色等于透明,它将检测为背景并绕过点击。
**创建 2 个函数**
- 设置绘图缓存
- onTouchImageTransparent
setDrawingCache
public void setDrawingCache(View view){
view.setDrawingCacheEnabled(true);
view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
view.buildDrawingCache(true);
}
onTouchImageTransparent
public boolean onTouchImageTransparent(View view, MotionEvent motionEvent){
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
Bitmap bmp = Bitmap.createBitmap(view.getDrawingCache());
if (motionEvent.getX() < bmp.getWidth() && motionEvent.getY() < bmp.getHeight()) {
//Get color at point of touch
int color = bmp.getPixel((int) motionEvent.getX(), (int) motionEvent.getY());
bmp.recycle();
if (color == Color.TRANSPARENT) {
//do not proceed if color is transparent
Log.d("onTouch","Click on Background PNG");
return false;
} else {
//proceed if color is not transparent
Log.d("onTouch","Click on Image");
return true;
}
}else{
Log.d("onTouch","Click on somewhere else");
return false;
}
}else{
Log.d("onTouch","Click on Background");
}
return false;
}
然后将您的 onTouch 侦听器设置为您的图像视图
ImageView mImageView = findViewById(R.id.imageView);
setDrawingCache(mImageView);
mImageView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if(onTouchImageTransparent(view,motionEvent)){
//action goes here
}
return onTouchImageTransparent(view,motionEvent);
}
});