不规则按钮

本文介绍了一种在Android中实现不规则形状按钮的方法,通过在触摸事件中判断触点的像素值来确定是否点击在按钮的有效区域内。此方法适用于需要自定义按钮形状的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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);
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值