我想做一个多点可触摸的ImageView
。我做了一个ontouchlistener
来获得坐标x
和y
的触摸位置,并为每个区域做出反应。它在1080*1960
屏幕上完美运行,但对于720*1276
,坐标会发生变化,整个事情都会出错。有任何想法吗?
ImageView
部分代码
float x = motionEvent.getX();
float y = motionEvent.getY();
String message = String.format("Coordinates: (%.2f, %.2f)",x,y);
//Toast.makeText(Study.this,message,Toast.LENGTH_SHORT).show();
//To make the image clickable by Coordinates of touch
if(x> 179 && x< 405 && y> 37 && y< 145 ){
Toast.makeText(Study.this,"prep",Toast.LENGTH_SHORT).show();
}else if (x>= 405 && x < 550 && y >= 30 && y <135){
Toast.makeText(Study.this,"1",Toast.LENGTH_SHORT).show();
}else if (x>= 570 && x < 684 &&y >= 49 && y < 190){
Toast.makeText(Study.this,"2",Toast.LENGTH_SHORT).show();
}else if (x>= 675 && x < 822 &&y >= 143 && y < 315){
Toast.makeText(Study.this,"3",Toast.LENGTH_SHORT).show();
}else if (x>= 757 && x < 870 &&y >= 290 && y < 447){
Toast.makeText(Study.this,"4",Toast.LENGTH_SHORT).show();
}else if (x>= 346 && x < 686 &&y >= 760 && y < 845){
Toast.makeText(Study.this,"1st",Toast.LENGTH_SHORT).show();
}else if (x>= 30 && x < 240 &&y >= 460 && y < 850){
Toast.makeText(Study.this,"2nd",Toast.LENGTH_SHORT).show();
}else if (x>= 240 && x < 755 &&y >= 150 && y < 750) {
}
return false;
使用以下代码行来获取屏幕的像素密度,像素宽度和高度(以像素为单位):
public static final double SCALE = Resources.getSystem().getDisplayMetrics().density;
public static final int WIDTH = Resources.getSystem().getDisplayMetrics().widthPixels;
public static final int HEIGHT = Resources.getSystem().getDisplayMetrics().heightPixels;
现在在if语句中使用这些常量,如下所示:
if((x > WIDTH / 2 - SCALE * 50) && (x < WIDTH / 2 + SCALE * 50) && (Y > HEIGHT/ 2 - SCALE * 50) && (Y < HEIGHT/ 2 + SCALE * 50)){
Toast.makeText(Study.this,"prep",Toast.LENGTH_SHORT).show();
}
如果用户要触摸宽度为100,高度为100且位于屏幕中心的正方形,则上面的代码将显示吐司。
所有设备的大小和相对位置将相同。