@@ -27,9 +27,9 @@ class MyCanvas(context: Context, attrs: AttributeSet) : View(context, attrs) {
2727 var mBackgroundBitmap: Bitmap ? = null
2828 var mListener: CanvasListener ? = null
2929
30- // allow undoing Clear
3130 var mLastPaths = LinkedHashMap <MyPath , PaintOptions >()
3231 var mLastBackgroundBitmap: Bitmap ? = null
32+ var mUndonePaths = LinkedHashMap <MyPath , PaintOptions >()
3333
3434 private var mPaint = Paint ()
3535 private var mPath = MyPath ()
@@ -67,16 +67,32 @@ class MyCanvas(context: Context, attrs: AttributeSet) : View(context, attrs) {
6767 return
6868 }
6969
70- if (mPaths.isEmpty())
70+ if (mPaths.isEmpty()) {
7171 return
72+ }
7273
74+ val lastPath = mPaths.values.lastOrNull()
7375 val lastKey = mPaths.keys.lastOrNull()
7476
7577 mPaths.remove(lastKey)
78+ if (lastPath != null && lastKey != null ) {
79+ mUndonePaths[lastKey] = lastPath
80+ mListener?.toggleRedoVisibility(true )
81+ }
7682 pathsUpdated()
7783 invalidate()
7884 }
7985
86+ fun redo () {
87+ val lastKey = mUndonePaths.keys.last()
88+ addPath(lastKey, mUndonePaths.values.last())
89+ mUndonePaths.remove(lastKey)
90+ if (mUndonePaths.isEmpty()) {
91+ mListener?.toggleRedoVisibility(false )
92+ }
93+ invalidate()
94+ }
95+
8096 fun toggleEraser (isEraserOn : Boolean ) {
8197 mIsEraserOn = isEraserOn
8298 mPaintOptions.isEraser = isEraserOn
@@ -146,7 +162,7 @@ class MyCanvas(context: Context, attrs: AttributeSet) : View(context, attrs) {
146162 }
147163
148164 fun addPath (path : MyPath , options : PaintOptions ) {
149- mPaths.put( path, options)
165+ mPaths[ path] = options
150166 pathsUpdated()
151167 }
152168
@@ -248,6 +264,8 @@ class MyCanvas(context: Context, attrs: AttributeSet) : View(context, attrs) {
248264 mStartX = x
249265 mStartY = y
250266 actionDown(x, y)
267+ mUndonePaths.clear()
268+ mListener?.toggleRedoVisibility(false )
251269 }
252270 MotionEvent .ACTION_MOVE -> actionMove(x, y)
253271 MotionEvent .ACTION_UP -> actionUp()
0 commit comments