近日,在開發拼接圖片中實現剪下圖片並把背景色設為透明,在此分享一下實現的方法
首先為確保顏色去除後變成透明,圖片品質必須是Config.ARGB_4444,或者Config.ARGB_8888,通過以下方法對資源圖進行轉換
bmp = bmp.copy(Bitmap.Config.ARGB_8888, true);
然後就可以進行過濾了,代碼如下:
Canvas c = new Canvas(bmp);Paint p = new Paint();p.setAlpha(0);p.setXfermode(new AvoidXfermode(removeColor, 0, AvoidXfermode.Mode.TARGET));c.drawPaint(p);return bmp;
關於setXfermode()方法的用法可參考http://yueguc.iteye.com/blog/782109
轉換後再對資源圖通過以下方法進行剪下,以擷取我們所需的圖塊
Bitmap tileImg = Bitmap.createBitmap(sourceImg, xIndex, yIndex, set.tileWidth, set.tileHeight);
然而,在圖塊剪下出來後,我們卻發現這不是我們想要的效果,背景色變成黑色,而不是透明的。
通過測試發現
Bitmap.createBitmap(sourceImg, xIndex, yIndex, set.tileWidth, set.tileHeight);
不論資源圖是多少位,建立的圖片會被轉換成RGB_565,所以不支援透明通道。
在網上檢索中發現了另外一種剪下方法,該方法能保留原圖的品質
public static Bitmap cutBitmap(Bitmap mBitmap, Rect r, Bitmap.Config config) { int width = r.width(); int height = r.height(); Bitmap croppedImage = Bitmap.createBitmap(width, height, config); Canvas canvas = new Canvas(croppedImage); Rect dr = new Rect(0, 0, width, height); canvas.drawBitmap(mBitmap, r, dr, null); return croppedImage;}
最後驗證該方法可行。如果有其它實現方式,歡迎留言交流心得!