1

我正在创建一个绘图应用程序。我有一个带有 Canvas 的自定义视图,它根据用户输入绘制线条:

class Line {
  float startX, startY, stopX, stopY;
  public Line(float startX, float startY, float stopX, float stopY) {
    this.startX = startX;
    this.startY = startY;
    this.stopX = stopX;
    this.stopY = stopY;
  }
  public Line(float startX, float startY) { // for convenience
    this(startX, startY, startX, startY);
  }
}

public class DrawView extends View {
  Paint paint = new Paint();
  ArrayList<Line> lines = new ArrayList<Line>();

  public DrawView(Context context, AttributeSet attrs) {
    super(context, attrs);

    paint.setAntiAlias(true);
    paint.setStrokeWidth(6f);
    paint.setColor(Color.BLACK);
    paint.setStyle(Paint.Style.STROKE);
    paint.setStrokeJoin(Paint.Join.ROUND);
  }

  @Override
  protected void onDraw(Canvas canvas) {
    for (Line l : lines) {
      canvas.drawLine(l.startX, l.startY, l.stopX, l.stopY, paint);
    }
  }

  @Override
  public boolean onTouchEvent(MotionEvent event) {

    if (event.getAction() == MotionEvent.ACTION_DOWN) {
      lines.add(new Line(event.getX(), event.getY()));
      return true;
    }
    else if ((event.getAction() == MotionEvent.ACTION_MOVE ||
        event.getAction() == MotionEvent.ACTION_UP) &&
        lines.size() > 0) {
      Line current = lines.get(lines.size() - 1);
      current.stopX = event.getX();
      current.stopY = event.getY();
      Invalidate();
      return true;
    }
    else {
      return false;
    }
  }
}

我想要做的是将这些行保存到一个文本文件中,以便用户以后可以加载它们。如何保存它们然后加载它们?

4

1 回答 1

2

我建议使用 GSON 库将 JSON 序列化为文件。https://sites.google.com/site/gson/gson-user-guide有一个很好的教程

于 2013-05-28T03:40:06.517 回答