我有一个图像按钮,当按下时,我希望它指向用户的手指(等。就像一个字符如何在视频游戏中看用户的鼠标)。然而,它不工作,它不正确跟踪手指。我认为这与我的逻辑有关,但我不确定。
下面是我的代码:
findViewById<ImageButton>(R.id.leftButton).setOnTouchListener { _, motionEvent ->
//Will happen when image is pressed other wise event is set to false
when (motionEvent.action){
//change opacity of nob direction image when user holds finger on image
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_MOVE -> {
//remove directional image (not the image moving)
findViewById<ImageView>(R.id.leftButtonDerection).alpha = 0.0f
//get y and x value of finger
val x: Float = motionEvent.x
val y: Float = motionEvent.y
//find x and y value for nob image (this is where I think the problem is)
val nobCenterX = (findViewById<ImageButton>(R.id.leftButton).x + findViewById<ImageButton>(R.id.leftButton).width) / 2
val nobCenterY = (findViewById<ImageButton>(R.id.leftButton).y + findViewById<ImageButton>(R.id.leftButton).height) / 2
//calculate angle from finger to nob point
val angle = Math.toDegrees(atan2(y - nobCenterY, x - nobCenterX).toDouble())
//apply angle to nob image rotation
findViewById<ImageButton>(R.id.leftButton).rotation = angle.toFloat()
}
//when user lets go or the hold action is stopped
//it will reset the opacity of the direction image
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
findViewById<ImageView>(R.id.leftButtonDerection).alpha = 1.0f
findViewById<ImageButton>(R.id.leftButton).rotation = 0f
}
}
false
}
字符串
输出代码:
我想要的是图像能够做一个完整的360,所以它可以按照手指在任何位置一旦按下。
谢谢你的帮助
1条答案
按热度按时间qco9c6ql1#
第一个问题是你认为它在哪里,按钮中心坐标与触摸坐标无关。
字符串
第二个问题是,你正在旋转同一个视图,你正在监听触摸事件,这将导致抖动旋转。我建议你在你的内部视图(
leftButtonDerection
)上监听触摸事件,并旋转外部视图(leftButton
)。