2014-11-25 50 views
0

我有以下代碼在畫布上繪製。該代碼來自SO和Android SDK演示,我已經將其刪除以更好地解釋我的問題。代碼基本上可以工作,但是隨着時間的推移,alpha繪圖的較舊部分會變暗,因爲它會在onDraw()中反覆繪製位圖(使用SDK中演示的實線時不會出現問題,但它會變成一個使用alpha時)。我可以使用一個位圖繪製Alpha嗎?

Drawing

public class CanvasView extends View { 

    public void init() { 
     bitmap = Bitmap.createBitmap(1280, 720, Bitmap.Config.ARGB_8888); // a bitmap is created 
     canvas = new Canvas(bitmap); // and a canvas is instantiated 
    } 

    // Events 
    @Override public boolean onTouchEvent(@Nonnull MotionEvent event) { 

     float x = event.getX(); float y = event.getY(); 

     switch (event.getAction()) { 
      case MotionEvent.ACTION_DOWN: // when the user touches down 
       path.reset(); // the previous path is reset (if any) 
       drawingTool.down(); // my own class which encapsulates path.moveTo() 
       break; 

      case MotionEvent.ACTION_MOVE: // when the user paints 
       Rect dirtyRect = drawingTool.move(x, y); // encapsulates path.quadTo() // the path is built 
       if (dirtyRect != null) { invalidate(dirtyRect); } // and the dirty rectangle is invalidated 
       break; 

      case MotionEvent.ACTION_UP: // when the user lifts the finger 
       canvas.drawPath(path, paint); // the final path is drawn 
       path.reset(); 
       invalidate(); // and the full area invalidated (just to make sure the final drawing looks as it should) 
       break; 
     } 
     return true; 
    } 

    @Override protected void onDraw(@Nonnull Canvas canvas) { // after every move or up event 
     super.onDraw(canvas); 

     canvas.drawBitmap(bitmap, 0, 0, null); // the previous bitmap is drawn [here is the problem] 
     canvas.drawPath(path, paint); // and the new path is added 
    } 
} 

的問題發生在的onDraw(),因爲該位圖繪製了個遍。所以每當新路徑完成時,以前的繪圖變得更暗。

我知道我可以採取第二個位圖並緩存每個路徑繪製後的結果,然後應用每個新路徑的「乾淨」位圖。但這會很昂貴。

有沒有辦法在不使用第二個位圖的情況下繪製alpha線或在每個路徑之後重新繪製所有內容?我正在尋找一種便宜的解決方案。

這裏的問題是位圖和畫布直接耦合,所以當我在畫布上繪製時,結果立即反映在位圖中。所以我不能只清除一個或另一個?

回答

0

我與此播放了一段時間,我意識到,該溶液是如的onDraw切換兩個命令一樣簡單。

而不是

canvas.drawBitmap(bitmap, 0, 0, null); 
    canvas.drawPath(path, paint); 

使用

canvas.drawPath(path, paint); 
    canvas.drawBitmap(bitmap, 0, 0, null); 

繪製位圖最後解決問題。繪畫時它仍然太暗,所以需要更多的調整,但主要問題已經解決。

另外,它的好處是我不需要第二個位圖。但同樣清楚的是,第二個位圖沒有多大意義,因爲我的位圖已經在緩存圖像,onDraw()只是將它繪製到視圖中。

0

實際上,您可以將Alpha級別設置爲Paint對象。例如:

Paint transparentpaint = new Paint(); 
transparentpaint.setAlpha(100); // 0 - 255 

canvas.drawBitmap(bitmap, 0, 0, transparentpaint); 

嘗試粘貼此代替canvas.drawBitmap(bitmap, 0, 0, null);

+0

謝謝,但我認爲這不會解決我的問題,因爲它使整個位圖更透明,而這不是我想要的。用戶可以用不同的alpha來繪製線條,並且線條應該保留繪製它的alpha。它給我帶來了這個想法,儘管可能使用PorterDuff模式(最黑暗)繪製位圖,但我認爲這不是一個好主意,因爲它在清除路徑時會產生副作用。 – 2014-11-25 15:44:25

相關問題