gpt4 book ai didi

android - 方向改变时如何在 Canvas 中重绘绘图

转载 作者:行者123 更新时间:2023-12-05 00:07:33 26 4
gpt4 key购买 nike

在 table 或设备旋转之前,我的代码工作正常。旋转时绘图被清除,我了解到它会发生,因为当设备旋转时, Activity 会重新启动。我的问题是如何重绘并将数据保存到 onSaveInstanceState。许多人说我必须使用 onSaveInstanceState 来保存绘图,但是当我必须保存的数据类型是 Path 时,我不知道该怎么做。

这是我的代码 fragment

public class MyDrawView extends View implements OnTouchListener {
MyDrawView drawView;
float prevX = 0;
float prevY = 0;

private Bitmap mBitmap;
private Canvas mCanvas;
private Path mPath;
private Paint mBitmapPaint;
private Paint mPaint;
private int w,h;
private ArrayList<Path> paths = new ArrayList<Path>();
private ArrayList<Paint> bitPaints = new ArrayList<Paint>();
private ArrayList<Paint> pathPaints = new ArrayList<Paint>();
Paint tempPaint;
private String filename="";

public MyDrawView(Context c,String filename) {
super(c);
mPath = new Path();
mBitmapPaint = new Paint(Paint.DITHER_FLAG);


this.filename=filename;
setFocusable(true);
setFocusableInTouchMode(true);
this.setOnTouchListener(this);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(Color.RED);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(6);
tempPaint=new Paint(mPaint);
mCanvas = new Canvas();
mPath = new Path();
if (rotated){
setDefaultDrawing();
}

}
public void setDefaultDrawing()
{

}
public Bitmap getBitmap(){
return this.mBitmap;
}
public void setStrokeWidth(float width){
mPaint.setStrokeWidth(width);
}
public void setColor(int color){
mPaint.setColor(color);
}
public String getFileName(){
return this.filename;
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
this.w=w;
this.h=h;
mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
Path tempPath=new Path(mPath);
paths.add(tempPath);
Paint tempPaint=new Paint(mPaint);
pathPaints.add(tempPaint);
Paint tempBitPaint=new Paint(mBitmapPaint);
bitPaints.add(tempBitPaint);
}

@Override
protected void onDraw(Canvas canvas) {
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);

canvas.drawPath(mPath, mPaint);
}

最佳答案

我想通了,因为 Path 是一个自定义对象,我创建了一个类对象来保存 Path,这样,我就可以将类对象保存在我的 onSaveInstanceState 中,并使用相同的类对象检索它。

关于android - 方向改变时如何在 Canvas 中重绘绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13851950/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com