友盟分享圆角icon到微信时会显示黑边,原因是微信对于透明背景会裁剪掉.
对于一般情况是可以通过给图片设置为PNG解决.
umImage = new UMImage(url);
umImage.compressFormat = Bitmap.CompressFormat.PNG;
umWeb.setThumb(umImage); //缩略图
但是例如分享到微信朋友圈还是会有黑边 .
包括一些其他的app貌似也有这种情况 要么是直角,要么也有黑边.
如果是从本地res目录下获取icon可以取和分享面板同样背景的圆角图(比如:圆角icon四个角都是透明的 , 可以将四个角的透明色改为分享出去的背景色,这样看起来是圆角.) , 然而我的需求并不允许我这样做, 所以这种方式并不适合我.
在网上查询了一些资料发现并无很好的解决方案.
最终得到以下方案:
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;
}
最终效果图