Android主介面的應用程式圖示風格迥異,為了使使用者看上去感覺比較統一,決定對其表徵圖進行設定統一背景。
在ApplicationPackageManager.java裡有個public Drawable getDrawable(String packageName, int resid,ApplicationInfo appInfo) 的方法用於返回應用的表徵圖。所以,我們可以在解析完成並在它被放入到緩衝cache裡面前,就對表徵圖進行處理,使之成為我們想要的效果。
//icon:擷取的應用程式圖示 idImg:想要添加的背景view id
private Drawable buildTrayForIcon(Drawable icon, int idImg){
Resources res = this.getResources();
BitmapDrawable bd = new BitmapDrawable(buildTrayForIcon(icon, BitmapFactory.decodeResource(res, idImg)));
bd.setTargetDensity(res.getDisplayMetrics());
return bd;
}
private Bitmap buildTrayForIcon(Drawable icon, Bitmap background){
if(icon == null){
return null;
}
final int backgroundWith = background.getWidth();
final int backgrouncHeight = background.getHeight();
int sourceWidth = icon.getIntrinsicWidth();
int sourceHeight = icon.getIntrinsicHeight();
/**
* 這裡需要做的工作是:如何確保原圖會在要加的中間
* 如果原圖比背景圖要大的話就會使原圖畫不出來。所以這時候
* 給出了一個固定的大小值來限定,right-left小於原圖的寬,
* 或者bottom-top小於原圖的高 將原圖進行縮放
*/
int left = (backgroundWith - sourceWidth) / 2;
int top = (backgrouncHeight - sourceHeight) / 2 ;
int right=left+sourceWidth;
int bottom=top+sourceHeight;
if(left<0 ){
left=0;
left+=15;//這些值可以自己進行看情況設定,我這隻是一個測試版
right=backgroundWith-15;
}
if(top<0){
top=0;
top+=15;
bottom=backgrouncHeight-15;
}
Bitmap compoundBitmap = null;
compoundBitmap = Bitmap.createBitmap(backgroundWith, backgrouncHeight, Config.ARGB_8888);
//Drawable d=new Drawable(compoundBitmap);
//Drawable drawable = new BitmapDrawable(compoundBitmap);
Canvas canvas = new Canvas(compoundBitmap);
canvas.drawBitmap(background, 0, 0, null);
//Rect r=drawable.getBounds();
//sOldBounds.set(icon.getBounds().left,);
//icon.setBounds(left, top, left+width, top+height);
icon.setBounds(left, top, right, bottom);
icon.draw(canvas);
//icon.setBounds(sOldBounds);
return compoundBitmap;
}
這樣處理之後就能達到我們的效果了。