Android Canvas 如何儲存成圖檔


在 Android 中,

可以搭配 FileOutputStreamBitmap.compress,

將 Canvas 圖畫儲存成圖檔,

範例, 如下:
 Java 程式碼
public class helloWorld extends Activity {
   
    Bitmap vBitmap = Bitmap.createBitmap( 320
                    , 480
                    , Bitmap.Config.RGB_565
                    );
    Canvas vBitmapCanvas = new Canvas( vBitmap );
   
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       
        setContentView( new View(this){
           
            @Override
            protected void onDraw(Canvas canvas) {
                // TODO Auto-generated method stub
                super.onDraw(canvas);
               
                // 設定繪圖樣式
                Paint vPaint = new Paint();     // 繪製樣式物件
                vPaint.setColor( 0xff00ffff );  // 畫筆顏色
                vPaint.setAntiAlias( true );    // 反鋸齒
                vPaint.setStyle( Paint.Style.STROKE );
               
                // 繪製一個弧形
                vBitmapCanvas.drawArc(new RectF(60, 120, 260, 320), 0, 240, true, vPaint );
               
                // 把 Bitmap 繪製到 Canvas 上
                canvas.drawBitmap( vBitmap, 0, 0, null );
               
                try {
                    // 輸出的圖檔位置
                    FileOutputStream fos = new FileOutputStream( "/sdcard/tomkuo139/draw.png" );
                   
                    // 將 Bitmap 儲存成 PNG / JPEG 檔案格式
                    vBitmap.compress( Bitmap.CompressFormat.PNG, 100, fos );
                   
                    // 釋放
                    fos.close();
                }
                catch (IOException e)
                {}
            }
        });
    }
}

儲存結果 :


Related Posts Plugin for WordPress, Blogger...