android - 为同一图像的不同部分设置点击侦听器
问题描述
我有一个看起来像这样的单一身体图像
我需要做的是区分点击身体的不同部位。例如,如果点击了头部,那么onHeadClicked
应该执行一个函数。如果我点击左手,那么一个函数onLeftHandClicked
。这将如何运作?
解决方案
首先,您必须将身体点的坐标存储在实际图像中。然后只需检查点击坐标是否在身体点的坐标内。您还应该确保使用图像视图的矩阵及其在屏幕上的坐标来缩放点
例如,如果
class BodyPoint{
String name;
int x;
int y;
public(String name,int x,int y){
this.name = name;
this.x = x;
this.y = y;}
}
BodyPoint headCoordinates = new BodyPoint ("head",50,20);
BodyPoint neckCoordinates = new BodyPoint ("neck",50,50);
BodyPoint leftHandCoordinates = new BodyPoint ("leftHand",10,50);
BodyPoint rightHandCoordinates = new BodyPoint ("rightHand",80,50);
BodyPoint[] bodyCoordinates = new BodyPoint[]{headCoordinates,neckCoordinates,
leftHandCoordinates ,rightHandCoordinates };
yourImgView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int[] viewCoords = new int[2];
yourImgView.getLocationOnScreen(viewCoords);
int touchX = (int) event.getX();
int touchY = (int) event.getY();
int imageX = touchX - viewCoords[0]; // viewCoords[0] is the X coordinate
int imageY = touchY - viewCoords[1];
Matrix mMatrix = getImageMatrix();
float[] f = new float[9];
mMatrix .getValues(f);
float scaleX = f[Matrix.MSCALE_X];
float scaleY = f[Matrix.MSCALE_Y];
processTouchedPoints(imageX/(int)scaleX , imageY/(int)scaleY );
return true;
}
});
...
int range = 50;
void processTouchedPoints(int imageX,int imageY){
foreach(BodyPoint mBodyPoint:bodyCoordinates ){
int x = mBodyPoint.x;
int y = mBodyPoint.y;
if((imageX> (x-range) && imageX<(x+range))
&&(imageY> (y-range) && imageY<(y+range))){
doWhatever(mBodyPoint.name)
}
}
}
推荐阅读
- python - Folium(具有不同数据源的地图)
- reactjs - 有没有办法明确设置 React Final-Form 脏?
- kotlin - 检查 Kotlin 不可变列表中的值
- javascript - 如何创建一个独立的、普通的 javascript 缩小版的电容器社区 http 模块示例
- python - 无法安装 pip install sphinxcontrib-openapi - “默认为用户安装,因为普通站点包不可写”
- java - 工件演示:war:java.lang.Exception:{“WFLYCTL0412:未安装的必需服务:”=>
- sql - R:带有接受 Excel 列表(列)的 where 语句的 dbGetQuery 函数
- python-3.x - 如何在脚本中使用标志?
- reactjs - 如何在反应中通过 onClick 获取卡 ID?
- spring - Spring ConfigurationProperties 未从 application.yml 加载值(默认)