Android:如何在屏幕方向更改时保存自定义手指绘图视图

4
我正在尝试创建一个自定义视图,用户可以在其中绘制他们的签名。您可以将其编程放入视图中并设置大小等信息。我以Android API演示中的fingerpaint类为基础,因为以前没有做过这件事。目前的问题是,在方向更改时它会擦除对象,我不确定如何防止它发生。
PaintView的代码:
private Bitmap  mBitmap;
private Canvas  mCanvas;
private Path    mPath;
private Paint   mBitmapPaint;
private boolean mDrawPoint;

private int stateToSave;

private Paint mPaint;


public PaintView(Context context) {
    super(context);
    System.out.println("init");
    mPath = new Path();
    mBitmapPaint = new Paint(Paint.DITHER_FLAG);
    setupPaint();
}

private void setupPaint()
{
    mPaint = new Paint();
    mPaint.setAntiAlias(true);
    mPaint.setDither(true);
    mPaint.setColor(0xFF000000);
    mPaint.setStyle(Paint.Style.STROKE);
    mPaint.setStrokeJoin(Paint.Join.ROUND);
    mPaint.setStrokeCap(Paint.Cap.ROUND);
    mPaint.setStrokeWidth(4);
}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);
    System.out.println("w "+w+" h "+h+" oldw "+oldw+" oldh "+oldh);
    mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
    mCanvas = new Canvas(mBitmap);
}

@Override
protected void onDraw(Canvas canvas) {
    System.out.println("on draw");
    canvas.drawColor(0xFFAAAAAA);

    canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);

    canvas.drawPath(mPath, mPaint);
}

private float mX, mY;
private static final float TOUCH_TOLERANCE = 4;

private void touch_start(float x, float y) {
    mPath.reset();
    mPath.moveTo(x, y);
    mX = x;
    mY = y;
    mDrawPoint=true;
}
private void touch_move(float x, float y) {
    float dx = Math.abs(x - mX);
    float dy = Math.abs(y - mY);
    if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
        mDrawPoint=false;
        mPath.quadTo(mX, mY, (x + mX)/2, (y + mY)/2);
        mX = x;
        mY = y;
    }
}
private void touch_up() {
    if(mDrawPoint == true) {
        mCanvas.drawPoint(mX, mY, mPaint);
    } else {
        mPath.lineTo(mX, mY);
        // commit the path to our offscreen
        mCanvas.drawPath(mPath, mPaint);
        // kill this so we don't double draw
        mPath.reset();
    }
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    getParent().requestDisallowInterceptTouchEvent(true);
    float x = event.getX();
    float y = event.getY();

    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            touch_start(x, y);
            invalidate();
            break;
        case MotionEvent.ACTION_MOVE:
            touch_move(x, y);
            invalidate();
            break;
        case MotionEvent.ACTION_UP:
            touch_up();
            invalidate();
            break;
    }
    return true;
}

作为一个小测试,我添加了以下内容。
@Override
public Parcelable onSaveInstanceState() 
{
    System.out.println("save instance");
    stateToSave++;
    Bundle bundle = new Bundle();
    bundle.putParcelable("instanceState", super.onSaveInstanceState());  
    bundle.putInt("stateToSave", this.stateToSave);

    return bundle;
}

@Override
public void onRestoreInstanceState(Parcelable state) 
{
    System.out.println("on restore");
    if (state instanceof Bundle) 
    {
        System.out.println("on restore");
        Bundle bundle = (Bundle) state;
        this.stateToSave = bundle.getInt("stateToSave");
        super.onRestoreInstanceState(bundle.getParcelable("instanceState"));
        System.out.println(stateToSave);
        return;
    }
    super.onRestoreInstanceState(state);
}

但是在屏幕方向变化时,onRestoreInstance()和onSaveInstance()方法不会被调用。以下是我在activity的onCreate()方法中创建PaintView的代码。

RelativeLayout inner= (RelativeLayout) findViewById(R.id.inner);

    int width=600;
    int height=360;
    float X= 100;
    float Y=60;

    LayoutParams wrapped = new LayoutParams(width,height);

    PaintView painting=new PaintView(this);

    painting.setX(X);
    painting.setY(Y);
    painting.setLayoutParams(wrapped);
    inner.addView(painting);

编辑:我弄清楚了为什么saveinstancestate没有被调用,我必须给View一个ID,然后它才能正常工作。

painting.setId(4);

现在我需要想办法保存绘画。

1个回答

4

您需要确保您的视图(View)已经启用了 saveEnabled,请尝试:

setSaveEnabled(true);

你可以在PaintView的构造函数中实现这个功能。
此外,你可能需要确保当屏幕方向改变时,你的活动被销毁/重建。请确保不要有以下情况:
<activity name="?"
android:configChanges="keyboardHidden|orientation"
/>

如果未使用此View声明活动,则在方向更改时不会销毁该活动。此外,如果您在这些活动中重写了onSaveInstanceState/*onRestoreInstanceState*,则需要调用相应的超类方法,即super.onSaveInstanceState()或super.onRestoreInstanceState()。

关于如何实际重新创建或保存图像以进行方向更改,您可以将每个事件保存在某种可包含列表中。在onSaveInstanceState中保存该列表,并在onRestoreInstanceState中恢复它。然后,取出事件列表并遍历它,调用相应的绘制函数。您可能需要根据新的方向对X和Y值进行一些转换。

代码看起来应该像这样:

public class PaintView extends View {

    private static final String EXTRA_EVENT_LIST = "event_list";
private static final String EXTRA_STATE = "instance_state";
private ArrayList<MotionEvent> eventList = new ArrayList<MotionEvent>(100);

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        getParent().requestDisallowInterceptTouchEvent(true);           
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_MOVE:
            case MotionEvent.ACTION_UP:
            performTouchEvent(event);                
        }             
        return true;
    }

    private void performTouchEvent(MotionEvent event) {
        float x = event.getX();
            float y = event.getY();
        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
                touch_start(x, y);
                break;
            case MotionEvent.ACTION_MOVE:
                touch_move(x, y);
                break;
            case MotionEvent.ACTION_UP:
                touch_up();
                break;
                }
                invalidate();
                eventList.add(MotionEvent.obtain(event));           
        }
    }


    @Override
    public Parcelable onSaveInstanceState() 
    {
        System.out.println("save instance");
        Bundle bundle = new Bundle();
        bundle.putParcelable(EXTRA_STATE, super.onSaveInstanceState());  
        bundle.putParcelableArrayList(EXTRA_EVENT_LIST, eventList);

    return bundle;
    }

    @Override
    public void onRestoreInstanceState(Parcelable state) 
    {
        if (state instanceof Bundle) 
        {
            Bundle bundle = (Bundle) state;
            super.onRestoreInstanceState(bundle.getParcelable(EXTRA_STATE));
            eventList = bundle.getParcelableArrayList(EXTRA_EVENT_LIST);
            if (eventList == null) {
               eventList = new ArrayList<MotionEvent>(100); 
            }
            for (MotionEvent event : eventList) {
               performTouchEvent(event);
            }               
            return;
        }
        super.onRestoreInstanceState(state);
    }
}

我没有为视图设置ID,但我已经修复了它并且它可以工作。现在我需要弄清楚如何保存绘图。 - user2312638
保存旋转,我的意思是。 - user2312638
1
很高兴能够帮到你。如果这个答案有助于解决你的问题,你应该考虑给它点赞或接受它(这就是 Stack Overflow 的工作方式)。 - Matt Wolfe
你也可以创建一个 MotionEvent 对象的 ArrayList(它们实现了 Parcelable 接口)。只需确保在将事件添加到数组列表时调用 MotionEvent.obtain()。 - ars-longa-vita-brevis
2
它会抛出ConcurrentModificationException异常,因为在“restoreInstanceState()”中调用“performTouchEvent”时,“performTouchEvent”将事件重新添加到事件列表中。您必须在“restoreInstancesState()”中使用单独的ArrayList。 - Roel
显示剩余8条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接