如何创建这样的自定义按钮?
它应该只是可点击区域而不是真正的按钮。
最佳答案
我在我的应用程序中使用了大量不规则形状的按钮,要更改按钮的“热区”或“可点击区域”,我只需使用 Bitmap.getPixel()
方法来检查所用图像的 alpha。如果该方法返回0,则不执行点击事件。
例子:
(1) 按照您喜欢的任何方式,像往常一样创建您的按钮。
(2) 定义一个Bitmap
并为其分配用于按钮的相同图像drawable。
(3) 获取触摸或点击 Action 的X、Y坐标。
(4) 将坐标传递给 .getPixel(x,y)
方法。
示例代码:
// ** Declare your Bitmap somewhere **
final Bitmap TheBitmap;
TheBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.TheImage);
// ** My onTouch code **
public boolean onTouch(View v, MotionEvent event) {
int eventPadTouch = event.getAction();
switch (eventPadTouch) {
case MotionEvent.ACTION_DOWN:
if (iX>=0 & iY>=0 & iX<TheBitmap.getWidth() & iY<TheBitmap.getHeight()) { // ** Makes sure that X and Y are not less than 0, and no more than the height and width of the image.
if (TheBitmap.getPixel(iX,iY)!=0) {
// * A non-alpha area was clicked, do something
}
}
return true;
}
return false;
}
event.getX()
和 event.getY()
只是为您提供触摸按钮位置的坐标。
** 上面的示例是为了引导您朝着正确的方向前进。有一些检查要添加到代码中以确保没有错误发生。
关于Android:创建异形按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7778279/