我有一个经典ImageView
,它被调整大小以适应其父级match_parent
在两个轴上并且scaleType
是fitCenter
.
然而,我从事件中得到的坐标onTouch
是相对于ImageView
. 如何将它们转换为相对于图像本身的边界?
更新
我最终手动执行此操作。这是在 Scala 中,但可能很容易翻译成 Java:
// Long press on the screen adds a new interaction at that position
screenView onTouch {
(v: View, ev: MotionEvent) => {
// Create the image transformation matrix
val m = screenView.getImageMatrix
val d = screenView.getDrawable
val drawableRect = new RectF(0, 0, d.getIntrinsicWidth, d.getIntrinsicHeight)
val viewRect = new RectF(0, 0, screenView.getWidth, screenView.getHeight)
m.setRectToRect(drawableRect, viewRect, Matrix.ScaleToFit.CENTER)
m.invert(m)
// Convert the points inside the image
val points = Array(ev.getX, ev.getY)
m mapPoints points
// Compute normalized coordinates
current_x = points(0) / d.getIntrinsicWidth
current_y = points(1) / d.getIntrinsicHeight
// Only continue if we touched inside the image
!(current_x >= 0 && current_x <= 1 &&
current_y >= 0 && current_y <= 1)
}
}