如何根据透明度来判断不规则图形的点击位置-------------------Android studio

1、准备好你需要的图片,并且将每一个部分都拆分成一个完整的图片,不要改变它原来的位置

         将他放入drawable中,命名随意,不一样就行,这几个里面都可以放,如果图片太大,可以放xhdpi后面几个


2、然后命名几个xml文件,每一个文件都对应一张图片

        放入drawable中


3、编辑chrome.xml文件

        

        每一个都这么写

4、编辑你的主xml文件

        

5、添加自定义MenuViewItem

package wy.com.demo.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.FrameLayout;



public class MenuViewItem extends FrameLayout {



    private int width = -1;
    private int height = -1;
    private Bitmap bitmap;

    public MenuViewItem(Context context) {

        super( context);

    }

    public MenuViewItem(Context context, AttributeSet attrs, int defStyle) {

        super( context, attrs, defStyle);

    }

    public MenuViewItem(Context context, AttributeSet attrs) {

        super( context, attrs);

    }

    @Override

    public boolean onTouchEvent(MotionEvent event) {

        int action = event.getAction();
        if(action != MotionEvent.ACTION_DOWN) {

            return super.onTouchEvent( event);

        }

        int x = (int)event.getX();
        int y = (int)event.getY();

        if(width == -1 || height == -1) {
            Drawable drawable = ((StateListDrawable)getBackground()).getCurrent();
            bitmap = ((BitmapDrawable)drawable).getBitmap();
            width = getWidth();
            height = getHeight();

        }

        if(null == bitmap || x < 0 || y < 0 || x >= width || y >= height) {

            return false;

        }

        int pixel = bitmap.getPixel( x, y);

        if(Color.TRANSPARENT == pixel) {

            return false;

        }

        return super.onTouchEvent( event);

    }

}
6、编辑activity

        这个就没有什么可以说的了

    

     

这两步已经说明问题了,然后点击哪个,哪个就会根据透明度判断出你点击的位置

但是有时候你的背景和你的图形并不是匹配的,所以会有些算法需要自己去写,我并不会,你也可以固定偏移,或者根据比例来偏移,不过这些方法都会有误差,自己决定

猜你喜欢

转载自blog.csdn.net/MrLi_IT/article/details/80612237