1
我想使用具有「粘性」畫布的SurfaceView。即保持其狀態並且不會被ivalidated的一個。我跟着一個例子,說明如何設置一個支架,併爲繪圖使用一個單獨的線程。這個想法是,當觸摸SurfaceView的任何地方時,將調用drawStuff
,給定一些繪畫,並繪製一個隨機矩形。使用支架和獨立線程在畫布上繪圖不會在屏幕上顯示任何內容
雖然代碼執行完美,但最後還是沒有畫任何東西。
public class DrawingView extends SurfaceView implements Callback {
Paint currentPaint;
float verts[];
private Boolean drawing = false;
class DrawingThread extends Thread {
private SurfaceHolder surfaceHolder;
private SurfaceView surfaceView;
private Boolean isRunning = false;
public void setIsRunning(Boolean isRunning) {
this.isRunning = isRunning;
}
public DrawingThread(SurfaceHolder surfaceHolder, SurfaceView surfaceView) {
super();
this.surfaceHolder = surfaceHolder;
this.surfaceView = surfaceView;
}
@Override
public void run() {
while(isRunning) {
Canvas c = surfaceHolder.lockCanvas();
surfaceView.draw(c);
surfaceHolder.unlockCanvasAndPost(c);
}
}
}
DrawingThread thread;
public DrawingView(Context context) {
super(context);
this.setWillNotDraw(false);
this.setBackgroundColor(Color.WHITE);
this.getHolder().addCallback(this);
this.thread = new DrawingThread(getHolder(), this);
}
@Override
protected void onDraw(Canvas canvas) {
if (drawing) {
// TEST CODE. WILL NEVER USE THIS IN PRODUCTION
canvas.drawRect(new Rect(new Float(Math.random()*200).intValue(), 20, new Float(Math.random()*200).intValue(), 30), currentPaint);
drawing = false;
}
}
public void drawStuff(Paint paint) {
currentPaint = paint;
drawing = true;
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
thread.setIsRunning(true);
thread.start();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
thread.setIsRunning(false);
}
}
和油漆設置:
view.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.BLUE);
paint.setAlpha(55);
((DrawingView) v).drawStuff(paint);
//v.invalidate();
return false;
}
});