2014-01-10 38 views
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; 
    } 
}); 

回答

0

最後,你不實際繪製的事情,當你以爲你是。調用draw()會在您的UI線程上計劃繪製,但實際上並不會從後臺線程調用onDraw,因此您的Canvas對於曲面不再有效。您應該將您正在做的任何事情渲染到Bitmap對象中,並且當您準備好寫入表面時,通知UI線程。 UI線程然後可以鎖定曲面,將位圖繪製到Canvas中,然後解鎖並將Canvas貼到曲面上。

相關問題