Canvas是一個(gè)畫布,你可以建立一個(gè)空白的畫布,就直接new一個(gè)Canvas對(duì)象,不需要參數(shù)。
也可以先使用BitmapFactory創(chuàng)建一個(gè)Bitmap對(duì)象,作為新的Canvas對(duì)象的參數(shù),也就是說(shuō)這個(gè)畫布不是空白的,
如果你想保存圖片的話,最好是Bitmap是一個(gè)新的,而不是從某個(gè)文件中讀入進(jìn)來(lái)的,或者是Drawable對(duì)象。
然后使用Canvas畫第一張圖上去,在畫第二張圖上去,最后使用Canvas.save(int flag)的方法進(jìn)行保存,注意save方法里面的參數(shù)可以保存單個(gè)圖層,
如果是保存全部圖層的 話使用 save( Canvas.ALL_SAVE_FLAG )。
最后所有的信息都會(huì)保存在第一個(gè)創(chuàng)建的Bitmap中。代碼如下:
Java代碼
- /**
- * create the bitmap from a byte array
- *
- * @param src the bitmap object you want proecss
- * @param watermark the water mark above the src
- * @return return a bitmap object ,if paramter's length is 0,return null
- */
- private Bitmap createBitmap( Bitmap src, Bitmap watermark )
- {
- String tag = "createBitmap";
- Log.d( tag, "create a new bitmap" );
- if( src == null )
- {
- return null;
- }
- int w = src.getWidth();
- int h = src.getHeight();
- int ww = watermark.getWidth();
- int wh = watermark.getHeight();
- //create the new blank bitmap
- Bitmap newb = Bitmap.createBitmap( w, h, Config.ARGB_8888 );//創(chuàng)建一個(gè)新的和SRC長(zhǎng)度寬度一樣的位圖
- Canvas cv = new Canvas( newb );
- //draw src into
- cv.drawBitmap( src, 0, 0, null );//在 0,0坐標(biāo)開(kāi)始畫入src
- //draw watermark into
- cv.drawBitmap( watermark, w - ww + 5, h - wh + 5, null );//在src的右下角畫入水印
- //save all clip
- cv.save( Canvas.ALL_SAVE_FLAG );//保存
- //store
- cv.restore();//存儲(chǔ)
- return newb;
- }
對(duì)圖片進(jìn)行縮小的方法:
Java代碼
- /**
- * lessen the bitmap
- *
- * @param src bitmap
- * @param destWidth the dest bitmap width
- * @param destHeigth
- * @return new bitmap if successful ,oherwise null
- */
- private Bitmap lessenBitmap( Bitmap src, int destWidth, int destHeigth )
- {
- String tag = "lessenBitmap";
- if( src == null )
- {
- return null;
- }
- int w = src.getWidth();//源文件的大小
- int h = src.getHeight();
- // calculate the scale - in this case = 0.4f
- float scaleWidth = ( ( float ) destWidth ) / w;//寬度縮小比例
- float scaleHeight = ( ( float ) destHeigth ) / h;//高度縮小比例
- Log.d( tag, "bitmap width is :" + w );
- Log.d( tag, "bitmap height is :" + h );
- Log.d( tag, "new width is :" + destWidth );
- Log.d( tag, "new height is :" + destHeigth );
- Log.d( tag, "scale width is :" + scaleWidth );
- Log.d( tag, "scale height is :" + scaleHeight );
- Matrix m = new Matrix();//矩陣
- m.postScale( scaleWidth, scaleHeight );//設(shè)置矩陣比例
- Bitmap resizedBitmap = Bitmap.createBitmap( src, 0, 0, w, h, m, true );//直接按照矩陣的比例把源文件畫入進(jìn)行
- return resizedBitmap;
- }