Reputation: 63
I'm working on an Android app using Kotlin where users can draw paths (lines or curves) on images using Canvas. The goal is to extract only painted areas from the original image, while unpainted areas should be transparent.
However, the result I get shows wrong, The resulting image does not extract a bitmap drawn with colored lines, but rather extracts an entire delineated area.
Can anyone give me a solution? Thanks in advance.
Here is my current code for extracting the painted region:
class CustomImageView(context: Context, attrs: AttributeSet) : ImageView(context, attrs) {
private val path = Path()
private val paint = Paint().apply {
color = Color.RED
style = Paint.Style.STROKE
strokeWidth = 8f
}
private var drawCanvas: Canvas? = null
private lateinit var drawingBitmap: Bitmap
init {
setOnTouchListener { _, event ->
when (event.action) {
MotionEvent.ACTION_DOWN -> {
path.moveTo(event.x, event.y)
true
}
MotionEvent.ACTION_MOVE -> {
path.lineTo(event.x, event.y)
invalidate()
true
}
else -> false
}
}
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
drawCanvas = canvas
canvas.drawPath(path, paint)
}
fun getMaskedBitmap(originalBitmap: Bitmap): Bitmap {
val width = originalBitmap.width
val height = originalBitmap.height
val maskedBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(maskedBitmap)
canvas.drawColor(Color.TRANSPARENT)
val maskPaint = Paint().apply {
style = Paint.Style.FILL
color = Color.BLACK
isAntiAlias = true
}
canvas.drawPath(path, maskPaint)
val imagePaint = Paint().apply {
xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
}
canvas.drawBitmap(originalBitmap, 0f, 0f, imagePaint)
return maskedBitmap
}
}
This is error result after drawn
The sunflower image below is the result I want after drawing, the part of the image not drawn by the red line will disappear:
Upvotes: 1
Views: 59