不规则按钮

实现思路是点击时候去判断该点的像素值,如果是透明的则认为没有点击。代码如下

package com.dway.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ImageButton;

/**
 * 不规则按钮
 * @author ldw
 * 20191011
 */
@SuppressLint("AppCompatCustomView")
public class IrregularButton extends ImageButton {

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

    public IrregularButton(Context context) {
        super( context);
    }

    public IrregularButton(Context context, AttributeSet attrs, int defStyle) {
        super( context, attrs, defStyle);
    }

    public IrregularButton(Context context, AttributeSet attrs) {
        super( context, attrs);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();
        if(action == MotionEvent.ACTION_DOWN) {
            int x = (int)event.getX();
            int y = (int)event.getY();
            if(width == -1 || height == -1) {
                Drawable drawable = getBackground().getCurrent();
                bitmap = ((BitmapDrawable)drawable).getBitmap();
                width = getWidth();
                height = getHeight();
            }
            if(null == bitmap || x < 0 || y < 0 || x >= width || y >= height) {
                return false;
            }
            if(Color.TRANSPARENT == bitmap.getPixel( x, y)) {
                return false;
            }
        }
        return super.onTouchEvent( event);
    }

}

 

你可能感兴趣的:(Android)