友盟分享圓角icon到微信時會顯示黑邊,原因是微信對於透明背景會裁剪掉.
對於一般情況是可以通過給圖片設置爲PNG解決.
umImage = new UMImage(url);
umImage.compressFormat = Bitmap.CompressFormat.PNG;
umWeb.setThumb(umImage); //縮略圖
但是例如分享到微信朋友圈還是會有黑邊 .
包括一些其他的app貌似也有這種情況 要麼是直角,要麼也有黑邊.
如果是從本地res目錄下獲取icon可以取和分享面板同樣背景的圓角圖(比如:圓角icon四個角都是透明的 , 可以將四個角的透明色改爲分享出去的背景色,這樣看起來是圓角.) , 可惜我的是從後臺獲取的url圖片路徑所以這種方式並不適合我.
在網上查詢了一些資料發現並無很好的解決方案.
最終得到以下方案:
1. 查詢到的方法有:
1. 直接將圓角改爲直角.
2. 取本地圖片res不同的分享給不同底色icon.
2. 下面是我目前的解決方案.
解決思路:
1. 準備1張背景圖片.例如:微信朋友圈分享出去的灰色背景是F7F7F7,就準備相同色值的圖片(下面有提供).
2. 將你的icon圖與你準備好的背景圖合成一張圖片 icon在上 背景圖在下.
3. 將合成的圖片上傳給微信.
這張圖色值是我取自微信朋友圈分享面板背景色 , 如果這並不是你理想中的顏色 , 你也可以多弄幾張圖片根據不同分享場景分別處理.
下面是關鍵代碼
/**
* 開啓線程 url 轉bitmap 將圖片裁剪成 300*300 避免超過32k
* 裁剪後將背景圖和icon圖合成一張圖 避免黑色背景出現
*/
new Thread(new Runnable() {
@Override
public void run() {
URL imageurl = null;
try {
imageurl = new URL(img_url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) imageurl.openConnection();
conn.setDoInput(true);
conn.connect();
//取本地背景圖,用於合成
InputStream is = conn.getInputStream();
Resources res = activity.getResources();
Bitmap bmp = BitmapFactory.decodeResource(res, R.mipmap.share_icon);
//背景圖處理
Bitmap bitmap1 = BitmapUtil.resizeImage(bmp, 300, 300);
//icon處理
Bitmap bitmap2 = BitmapUtil.resizeImage(BitmapFactory.decodeStream(is), 300, 300);
//合成處理
Bitmap bitmap3 = BitmapUtil.toConformBitmap(bitmap1, bitmap2);
if(share_media == WEIXIN_CIRCLE) {
umImage = new UMImage(activity, bitmap3);
}else {
umImage = new UMImage(activity,bitmap2);
}
umImage.compressFormat = Bitmap.CompressFormat.PNG;
umWeb.setThumb(umImage); //縮略圖
is.close();
//調起分享面板
shareAction(activity,share_media);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
將圖片縮放成相應的尺寸
public static Bitmap resizeImage(Bitmap bitmap, int w, int h) {
Bitmap BitmapOrg = bitmap;
int width = BitmapOrg.getWidth();
int height = BitmapOrg.getHeight();
int newWidth = w;
int newHeight = h;
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
// if you want to rotate the Bitmap
// matrix.postRotate(45);
Bitmap resizedBitmap = Bitmap.createBitmap(BitmapOrg, 0, 0, width,
height, matrix, true);
return resizedBitmap;
}
圖片合成
public static Bitmap toConformBitmap(Bitmap background, Bitmap foreground) {
if (background == null) {
return null;
}
int bgWidth = background.getWidth();
int bgHeight = background.getHeight();
//create the new blank bitmap 創建一個新的和SRC長度寬度一樣的位圖
Bitmap newbmp = Bitmap.createBitmap(bgWidth, bgHeight, Bitmap.Config.ARGB_8888);
Canvas cv = new Canvas(newbmp);
//draw bg into
cv.drawBitmap(background, 0, 0, null);//在 0,0座標開始畫入bg
//draw fg into
cv.drawBitmap(foreground, 0, 0, null);//在 0,0座標開始畫入fg ,可以從任意位置畫入
//save all clip
cv.save();//保存
//store
cv.restore();//存儲
return newbmp;
}
最終效果圖