我正在创建一个主屏幕有七个按钮的游戏
这是一个示例图像,假设蓝色框是位于任何位置的按钮。形成一个图形软件,我知道左上角和右下角的坐标。我得到像这样的用户触及的点的坐标并显示成功的吐司
@Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
Height_Ratio = height/Background_Height;
Width_Ratio = width/Background_Width;
Play_Button_Left_Ratio = Play_Button_Left*Width_Ratio;
Play_Button_Right_Ratio = Play_Button_Right*Width_Ratio;
Play_Button_Top_Ratio = Play_Button_Top*Height_Ratio;
Play_Button_Bottom_Ratio = Play_Button_Bottom*Height_Ratio;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if(x > Play_Button_Left_Ratio && x < Play_Button_Right_Ratio && y > Play_Button_Top_Ratio && y < Play_Button_Bottom_Ratio)
Toast.makeText(this, "Success!", Toast.LENGTH_SHORT).show();
使用
获取设备的高度和宽度DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
height = displaymetrics.heightPixels;
width = displaymetrics.widthPixels;
我必须为七个按钮执行它是否有更有效的方法。上面的代码获取屏幕高度给出实际像素或密度独立像素?
答案 0 :(得分:0)
为什么不在按钮上使用OnClickListener?
答案 1 :(得分:0)
更改
int x = (int) event.getX();
int y = (int) event.getY();
到
int tx = (int) event.getX();
int ty = (int) event.getY();
避免混淆变量
触摸
if(tx>image.x&&tx<image.x+image.width&&ty>image.y&&ty<image.y+image.height){
//image clicked do something
}