我正在尝试实现四个自定义形状的按钮,如下图所示:
到目前为止,我做了什么:我拍摄了4张不同的照片-每张照片只有一种颜色可见(请参见上文)。图像的另一部分是透明的。结果是,我有四张相同大小的图片。
现在,我使用相对布局,将所有4张图片都添加到同一位置的 ImageView 中。由于透明,我可以看到所需的图片。
对于我的ImageView,我已经实现了onTouchListener并包含以下内容:
private class ImageOnTouchListener implements View.OnTouchListener {
private int categoryId;
public ImageOnTouchListener(int categoryId) {
this.categoryId = categoryId;
}
@Override
public boolean onTouch(View v, MotionEvent event) {
Bitmap bmp = Bitmap.createBitmap(v.getDrawingCache());
int x = (int) event.getX();
int y = (int) event.getY();
boolean isInsideBitmap = x < bmp.getWidth() && y < bmp.getHeight() && x >= 0 && y >= 0;
boolean isActionUp = event.getAction() == MotionEvent.ACTION_UP;
if (isInsideBitmap) {
int color = bmp.getPixel(x, y);
bmp.recycle();
if (color == Color.TRANSPARENT){
return false;
}
else {
if (isActionUp) {
buttonClick();
}
}
}else{
bmp.recycle();
}
return true;
}
}
这种方法有效,但是会消耗大量内存,因为我在移动手指时总是创建一个位图。我不太确定这是否是实现此目标的最佳方法。我有什么可以做的事情可以做得更有效吗?
最佳答案
利用这样的事实,当圆的中心为(0,0)时,可以使用方程x² + y² <= radius²
判断坐标是否属于圆,我认为以下方法应该起作用。
public class ImageOnTouchListener implements View.OnTouchListener {
// TODO Adjust this value
private static int QUADRANT_RADIUS = 100; // in pixels
// TODO Adjust this value
private static int SPACE_BETWEEN_QUADRANTS = 5; // in pixels
@Override
public boolean onTouch(View v, MotionEvent event) {
int relativeX = (int) (event.getX() - v.getX());
int relativeY = (int) (event.getY() - v.getY());
int center = QUADRANT_RADIUS + (SPACE_BETWEEN_QUADRANTS / 2);
boolean isInsideCircle = Math.pow(relativeX - center, 2) + Math.pow(relativeY - center, 2) <= Math.pow(center, 2);
boolean isInsideBottomLeftQuadrant = isInsideCircle &&
relativeX <= QUADRANT_RADIUS &&
relativeY >= QUADRANT_RADIUS + SPACE_BETWEEN_QUADRANTS;
boolean isInsideBottomRightQuadrant = isInsideCircle &&
relativeX >= QUADRANT_RADIUS + SPACE_BETWEEN_QUADRANTS &&
relativeY >= QUADRANT_RADIUS + SPACE_BETWEEN_QUADRANTS;
boolean isInsideTopLeftQuadrant = isInsideCircle &&
relativeX <= QUADRANT_RADIUS &&
relativeY <= QUADRANT_RADIUS;
boolean isInsideTopRightQuadrant = isInsideCircle &&
relativeX >= QUADRANT_RADIUS + SPACE_BETWEEN_QUADRANTS &&
relativeY <= QUADRANT_RADIUS;
boolean isActionUp = event.getAction() == MotionEvent.ACTION_UP;
if (isActionUp) {
if (isInsideBottomLeftQuadrant) {
// Handle bottom left quadrant click
buttonClick();
return true;
} else if (isInsideBottomRightQuadrant) {
// Handle bottom right quadrant click
} // etc.
}
return false;
}
}
您需要调整
QUADRANT_RADIUS
和SPACE_BETWEEN_QUADRANTS
的值,然后要么从单个 View 处理所有触摸事件(就像我的代码 fragment 一样),要么每个图像的触摸监听器稍有不同。关于android - Android中的自定义形状按钮-我做对了吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23653010/