在图像视图中检测触摸
我有一个图像视图,我可以在其中为我的游戏绘制游戏板。我需要获取相对于图像视图的触摸的 X、Y 值。例如:如果有人触摸了左上角的像素,它会返回 (0,0),或者说游戏板是 100,100 板,而我触摸了中间,我会得到 (50,50)...如何有人会这样做吗?
gameView.setOnTouchListener(new OnTouchListener(){
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN){
int x = (int) event.getX() / pieceSize;
int y = (int) event.getY() / pieceSize;
Log.d("Touch Event", "Touch event at "+ x + " " +y);
doMove(x, y);
Log.d("Move", "The move was " + doMove(x,y));
}
gameView.setImageBitmap(Draw(pieceSize));
return true;
}
});
I have an image view that I draw my game board in for my game. I need to get the X, Y of the touch relative to the image view. For example: If someone touched the very top left Pixel, it would return (0,0) or, say the game board was a 100,100 board, and I touched right in the middle I would get (50,50)...How would one do this?
gameView.setOnTouchListener(new OnTouchListener(){
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN){
int x = (int) event.getX() / pieceSize;
int y = (int) event.getY() / pieceSize;
Log.d("Touch Event", "Touch event at "+ x + " " +y);
doMove(x, y);
Log.d("Move", "The move was " + doMove(x,y));
}
gameView.setImageBitmap(Draw(pieceSize));
return true;
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
当触摸事件分派到视图时,
Called。并从事件对象中检索 x 和 y。
当然,可以通过在您正在处理的视图上设置 OnTouchListener 来实现。
You can use
Called when a touch event is dispatched to a view.
And retrieve x and y from the event object.
Of course, by setting an OnTouchListener on the view you are working on.
如果您已将触摸侦听器放置到 ImageView 上,则 event.getX() 和 event.getY() 应返回相对于 ImageView 的值。
if you've put a touch listener onto the ImageView, then event.getX() and event.getY() should return values that are relative to the ImageView.
您应该设置 OnTouchListener 以及事件的 getX 和 getY。关于这个问题有很多答案。例如这里A: 获取触摸的坐标Android 上的事件
You should set OnTouchListener and getX and getY of the event. Lots of answers on this one. For example hereA: Get the co-ordinates of a touch event on Android