I am drawing a smooth line over a customImageView and wanted to save the path in shared preferences so that I can redraw the same path whenever required.
Method for drawing smooth line :
protected Path mPath;
protected Paint mPaint;
protected Paint mPaintFinal;
protected Bitmap mBitmap;
protected Canvas mCanvas;
private SharedPreferences mPreferences;
private void onTouchEventSmoothLine(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
isDrawing = true;
mStartX = mx;
mStartY = my;
mPath.reset();
mPath.moveTo(mx, my);
Log.i("::ACTION_DOWN::", mStartX +" // " +mStartY);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
float dx = Math.abs(mx - mStartX);
float dy = Math.abs(my - mStartY);
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
mPath.quadTo(mStartX, mStartY, (mx + mStartX) / 2, (my + mStartY) / 2);
mStartX = mx;
mStartY = my;
}
mCanvas.drawPath(mPath, mPaint);
Log.i("::ACTION_MOVE::", mStartX +" // " +mStartY);
invalidate();
break;
case MotionEvent.ACTION_UP:
isDrawing = false;
mPath.lineTo(mStartX, mStartY);
Log.i("::ACTION_UP::", mStartX +" // " +mStartY);
mCanvas.drawPath(mPath, mPaintFinal);
saveCustomPath(mPath);
mPath.reset();
invalidate();
break;
}
}
Method for saving path:
public void saveCustomPath(Path mPath){
SharedPreferences.Editor prefsEditor = mPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(mPath);
prefsEditor.putString("MyPath", json);
prefsEditor.commit();
}
Method for retrieving path:
public Path retrieveCustomPath(){
if(mPreferences != null) {
Gson gson = new Gson();
String json = mPreferences.getString("MyPath", "");
Path path = gson.fromJson(json, Path.class);
return path;
}
return null;
}
While, Path object can not be saved/retrieved directly to/from disk/shared prefernces without serializing/deserializing, I am unable to implement it as suggested here, any help would be highly appreciated.