Android ImageView图片透明区域不响应点击事件,不规则图片透明区域响应点击事件
经常会在项目中用到透明图片,不规则图片,特别是做游戏的时候,需要对图片的透明区域的点击事件做特别处理。
一、先上图片文件transparent.png,图片中间区域与外围区域是非透明的,其它区域是透明的:
二、上布局文件test.xml
[html]
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:gravity="center"
android:id="@+id/mainLayout">
<ImageView android:id="@+id/ImageView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/transparent"/>
</LinearLayout>
三、上Activity,MainActivity.java:
[java]
package org.shuxiang.test;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
public class MainActivity extends Activity
{
private ImageView iv;
private Bitmap bitmap;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.test);
iv = (ImageView) findViewById(R.id.ImageView01);
bitmap = ((BitmapDrawable) (iv.getDrawable())).getBitmap();
iv.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("Test", "点击");
}
});
iv.setOnTouchListener(new OnTouchListener()
{
@Override
public boolean onTouch(View arg0, MotionEvent arg1)
{
// TODO Auto-generated method stub
if(bitmap.getPixel((int)(arg1.getX()),((int)arg1.getY()))==0)
{
Log.i("Test", "透明区域");
return true;//透明区域返回true
}
return false;
}
});
}
}
补充:移动开发 , Android ,