I was working on a custom imageview that can draw line on it, the problem is that the drawing area size is not exactly with the bitmap size.
For example, in the oth
KOTLIN SOLUTION FOR SAME (using anilanswer)
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.view.View.OnTouchListener
import android.widget.ImageView
class CustomEditImageView : ImageView, OnTouchListener {
var downx = 0f
var downy = 0f
var upx = 0f
var upy = 0f
lateinit var canvas: Canvas
lateinit var paint: Paint
lateinit var EditImagematrix: Matrix
constructor(context: Context?) : super(context) {
setOnTouchListener(this)
}
constructor(context: Context?, attrs: AttributeSet?) : super(
context,
attrs
) {
setOnTouchListener(this)
}
constructor(
context: Context?, attrs: AttributeSet?,
defStyleAttr: Int
) : super(context, attrs, defStyleAttr) {
setOnTouchListener(this)
}
fun setNewImage(alteredBitmap: Bitmap, bmp: Bitmap) {
canvas = Canvas(alteredBitmap)
paint = Paint()
paint.setColor(Color.GREEN)
paint.strokeWidth=18f
EditImagematrix = Matrix()
canvas.drawBitmap(bmp, EditImagematrix, paint)
setImageBitmap(alteredBitmap)
}
override fun onTouch(v: View?, event: MotionEvent): Boolean {
val action = event.action
when (action) {
MotionEvent.ACTION_DOWN -> {
downx = getPointerCoords(event)[0] //event.getX();
downy = getPointerCoords(event)[1] //event.getY();
}
MotionEvent.ACTION_MOVE -> {
upx = getPointerCoords(event)[0] //event.getX();
upy = getPointerCoords(event)[1] //event.getY();
canvas.drawLine(downx, downy, upx, upy, paint)
invalidate()
downx = upx
downy = upy
}
MotionEvent.ACTION_UP -> {
upx = getPointerCoords(event)[0] //event.getX();
upy = getPointerCoords(event)[1] //event.getY();
canvas.drawLine(downx, downy, upx, upy, paint)
invalidate()
}
MotionEvent.ACTION_CANCEL -> {
}
else -> {
}
}
return true
}
fun getPointerCoords(e: MotionEvent): FloatArray {
val index = e.actionIndex
val coords = floatArrayOf(e.getX(index), e.getY(index))
val matrix = Matrix()
imageMatrix.invert(matrix)
matrix.postTranslate(scrollX.toFloat(), scrollY.toFloat())
matrix.mapPoints(coords)
return coords
}
}
Activity
var bmp: Bitmap? = null
var alteredBitmap: Bitmap? = null
var image = extras.getString(AppConstants.IMAGE_URI).toString()
if (image.isNotEmpty()) {
val bmpFactoryOptions = BitmapFactory.Options()
bmpFactoryOptions.inJustDecodeBounds = true
bmp = BitmapFactory
.decodeStream(
File(image).inputStream(), null, bmpFactoryOptions
)
bmpFactoryOptions.inJustDecodeBounds = false
bmp = BitmapFactory
.decodeStream(
File(image).inputStream(), null, bmpFactoryOptions
)
alteredBitmap = Bitmap.createBitmap(
bmp!!.width,
bmp!!.height, bmp!!.config
)
editimageView.setNewImage(alteredBitmap!!, bmp!!)
XML FILE