I have this function that allows the user to paint on the screen. It works correctly in the emulator; where I touch, the screen is painted. However, when I tested it on my tablet, it is very offset. If I click in the middle of the screen, it paints in the bottom right corner. Does anyone know how to fix this offset?
private fun handleTouch(event: MotionEvent): Boolean {
val drawable = drawable ?: return false
val imageWidth = drawable.intrinsicWidth
val imageHeight = drawable.intrinsicHeight
val viewWidth = width
val viewHeight = height
val scaleX = viewWidth.toFloat() / imageWidth
val scaleY = viewHeight.toFloat() / imageHeight
val scale = Math.min(scaleX, scaleY)
val correctedX = ((event.x - (viewWidth - imageWidth * scale) / 2) / scale).toInt()
val correctedY = ((event.y - (viewHeight - imageHeight * scale) / 2) / scale).toInt()
when (event.action) {
MotionEvent.ACTION_MOVE -> {
drawOnImage(correctedX, correctedY)
return true
}
MotionEvent.ACTION_DOWN -> {
performClick()
return true
}
MotionEvent.ACTION_UP -> {
drawOnImage(correctedX, correctedY)
drawingListener?.onDrawing()
return true
}
}
return false
}
fun drawOnImage(x: Int, y: Int) {
val canvas = Canvas((drawable as BitmapDrawable).bitmap)
canvas.drawCircle(x.toFloat(), y.toFloat(), paint.strokeWidth / 2, paint)
invalidate()
}
xml
<com.my.app.CustomImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:contentDescription="paint" />