在图像视图中检测触摸

发布于 2024-12-26 18:24:29 字数 722 浏览 1 评论 0原文

我有一个图像视图,我可以在其中为我的游戏绘制游戏板。我需要获取相对于图像视图的触摸的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

北凤男飞 2025-01-02 18:24:29

您可以使用

onTouch(View v, MotionEvent event)

当触摸事件分派到视图时,

Called。并从事件对象中检索 x 和 y。

当然,可以通过在您正在处理的视图上设置 OnTouchListener 来实现。

You can use

onTouch(View v, MotionEvent event)

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.

稍尽春風 2025-01-02 18:24:29

如果您已将触摸侦听器放置到 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.

终难遇 2025-01-02 18:24:29

您应该设置 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文