Android中不规则图片按钮透明区域的点击效果

/**
 * 不规则"图形按钮控件"
 *
 */
public class TrapezoidImageButton extends ImageButton {

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

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

    public TrapezoidImageButton(Context context) {
    super(context);
    }
    
    @Override
    public boolean onTouchEvent(MotionEvent event) {
    if (isTouchPointInView(event.getX(),event.getY())||
        event.getAction() != MotionEvent.ACTION_DOWN){
        return super.onTouchEvent(event);
    }else{
        return false;
    }
    }

    protected boolean isTouchPointInView(float localX, float localY){
    Bitmap bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    draw(canvas);
    int x = (int)localX;
    int y = (int)localY;
    if (x < 0 || x >= getWidth())
        return false;
    if (y < 0 || y >= getHeight())
        return false;
    int pixel = bitmap.getPixel(x,y);
    if ((pixel&0xff000000) != 0){ //点在非透明区
        return true;
    }else{
        return false;
    }
    }
}

你可能感兴趣的:(Android中不规则图片按钮透明区域的点击效果)