将android.graphics.Path保存到共享首选项

时间:2018-03-12 09:58:38

标签: java android gson sharedpreferences

我在customImageView上绘制了一条平滑线,并希望在共享首选项中保存路径,以便我可以在需要时重绘相同的路径。

绘制平滑线的方法:

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;
    }
}

保存路径的方法:

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();
}

检索路径的方法:

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;
} 

虽然在没有序列化/反序列化的情况下无法直接向/从磁盘/共享偏好保存/检索Path对象,但我无法按照建议here实现它,任何帮助都将受到高度赞赏。

0 个答案:

没有答案