2014-06-10 104 views
1

我想將畫布轉換爲圖像並將其保存在設備上。但是當我將位圖設置爲畫布時,我得到錯誤java.lang.UnsupportedOperationException。 我全碼:Android setBitmap to canvas

public class SingleTouchEventView extends View { 
private Paint paint = new Paint(); 
private Path path = new Path(); 


public SingleTouchEventView(Context context, AttributeSet attrs) { 
    super(context, attrs); 

    paint.setAntiAlias(true); 
    paint.setStrokeWidth(6f); 
    paint.setColor(Color.WHITE); 
    paint.setStyle(Paint.Style.STROKE); 
    paint.setStrokeJoin(Paint.Join.BEVEL); 
} 

@Override 
protected void onDraw(Canvas canvas) { 
    canvas.drawPath(path, paint); 
    canvas.drawCircle(50, 50, 3, paint); 
    Bitmap bitmap = Bitmap.createBitmap(canvas.getWidth(), canvas.getHeight(), Bitmap.Config.ARGB_8888); 
    canvas.setBitmap(bitmap); 
    try { 

     File file = new File(Environment.getExternalStorageDirectory() + "/image.jpg"); 
     bitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(file)); 
    } catch (FileNotFoundException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 

}

也許有人可以幫我解決這個問題呢?

回答

5

這不是你如何畫一個位圖。你不使用繪製到屏幕上的畫布。您創建第二個畫布,將要繪製的位圖作爲參數傳入構造函數中。然後對該畫布的任何繪製命令將繪製位圖。然後,您將該位圖繪製到屏幕上。事情是這樣的:

Canvas myCanvas = new Canvas(myBitmap); 
myCanvas.drawLine(); 
myCanvas.drawCircle(); 
//Insert all the rest of the drawing commands here 
screenCanvas.drawBitmap(myBitmap, 0, 0); 

我也不會寫在onDraw有文件系統 - 我期望,如果你做的繪圖性能叫苦連天。單獨的函數調用可以做到這一點。如果將myBitmap保留在變量中,則可以隨時對其進行壓縮,以便將最後一次繪製寫入磁盤。