Implement Draw, Undo, Redo, Erase and Save in canvas - Jetpack Compose Android

135 views Asked by At

I am developing a drawing app with Jetpack Compose Canvas, I am able to draw on the canvas and undo/redo my hand-drawn strokes. I also need options to change the brush color and size. Finally, I want to save the image as both PNG and JPG.

I would be grateful for any code snippet, suggestions, references, or links.

1

There are 1 answers

0
liuwons On

change the brush color and size

You can create a Paint with stroke color and size like:

strokePaint = Paint().also { paint ->
    paint.isAntiAlias = true
    paint.style = STROKE
    paint.color = Color.RED
    paint.strokeWidth = 16
}

then draw your path with this Paint:

canvas.drawPath(path, strokePaint)

save the image as both PNG and JPG

You can achieve it by :

  1. create an Bitmap and Canvas with specific size:
val cacheBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val cacheCanvas = Canvas(cacheBitmap)
  1. draw your paths to this canvas
cacheCanvas.drawPath(path, strokePaint)
  1. save the Bitmap to file
val stream = FileOutputStream(Environment.getExternalStorageDirectory() + "/test.png");
/* Write bitmap to file using JPEG or PNG and 80% quality hint for JPEG. */
cacheBitmap.compress(CompressFormat.PNG, 80, stream);
stream.close();