天天看點

如何将Canvas中内容儲存為圖檔

view plain copy to clipboard print ?

  1. Bitmap bm = Bitmap.createBitmap( 320 ,  480 , Config.ARGB_8888);  
  2.         Canvas canvas = new  Canvas(bm);  
  3.         Paint p = new  Paint();  
  4.         canvas.drawRect(50 ,  50 ,  200 ,  200 , p);  
  5.         canvas.save(Canvas.ALL_SAVE_FLAG );  
  6.         canvas.restore();  
  7.         File f = new  File( "/sdcard/0.png" );  
  8.         FileOutputStream fos = null ;  
  9.         try  {  
  10.             fos = new  FileOutputStream(f);  
  11.             bm.compress(Bitmap.CompressFormat.PNG, 50 , fos);  
  12.         } catch  (FileNotFoundException e) {  
  13.             // TODO Auto-generated catch block   
  14.             e.printStackTrace();  
  15.         }  

  這樣就把Canvas中的内容儲存成了sd卡上的一個png圖檔。簡單說一下原理,自己create一個bitmap,然後讓Canvas通過這個bitmap建立一個執行個體,然後在該canvas上繪制的内容都會畫 在該bitmap上,儲存Canvas的圖層,然後把bitmap寫到sd卡上的檔案。注意:要在AndroidManifest.xml中添加在sd卡上讀寫檔案的權限