最近公司在做一个社交app,其中有分享功能(eg.分享到QQ)。分享的时候,需要将图片带到分享列表页面去。当时是这么写的:
byte[] iconBytes = bmpToByteArray(
drawableToBitmap(iv.getDrawable()), true);
public static byte[] bmpToByteArray(final Bitmap bmp,
final boolean needRecycle) {
ByteArrayOutputStream output = new ByteArrayOutputStream();
bmp.compress(CompressFormat.PNG, 100, output);
if (needRecycle) {
bmp.recycle();
}
byte[] result = output.toByteArray();
try {
output.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static Bitmap drawableToBitmap(Drawable drawable) {
int w = drawable.getIntrinsicWidth();
int h = drawable.getIntrinsicHeight();
Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565;
Bitmap bitmap = Bitmap.createBitmap(w, h, config);
Canvas canvas = new Canvas(bitmap);
//TODO
drawable.setBounds(0, 0, w, h);
drawable.draw(canvas);
return bitmap;
}
然后,要跳转的一瞬间:当前页面发生了意想不到的变化:
图片进行一个“莫名其妙”的变化呢?
不能理解啊!!难道说imageView.getDrawable()有猫腻?
暂时查不出来,可客户又等着发布新版本。无奈试着使用了一下:
iv.setDrawingCacheEnabled(true);
byte[] iconBytes = bmpToByteArray(iv.getDrawingCache(), false);
iv.setDrawingCacheEnabled(false);
这样就可以了。
晚上回去,我感觉很“各应”,这是怎么了?明天一定要好好查查。
唉,图片现在位于ImageView的左上角,其大小和原图相当。然后,通过屏幕截图和PS中图层的功能,将其放到一起,发现真的一样哎!这引起了我的好奇心。在drawableToBitmap方法中:
int w = drawable.getIntrinsicWidth();
int h = drawable.getIntrinsicHeight();
我打断点发现,这个就是原图的大小啊。为了进一步验证我的假设,我将w和h写的和原图(布局参数等完全调用之后的展示效果)一样,发现他就不“莫名其妙”了,而是“岿然不动”。更近了!我另w=200;h=200;发现图片位于ImageView区域的左上角,大小为200*200。我尝试的修改drawableToBitmap方法中的drawable.setBounds(0,100,200,200);
现在图片出现在距离ImageView区域上方 100px的位置。 我想起来了,在Java中除了基本类型为直接赋值外,其他的获取的都是引用,在获取ImageView中的drawable的时候,对drawable进行了setBounds操作,该操作指向的对象和ImageView的drawable是同一个对象。为了验证我的假设,从网上找了一个copy drawable的方法:
/**
* drawable 复制
*
* @param drawable
* @return
*/
public static Drawable getNewDrawable(Drawable drawable) {
return drawable.getConstantState().newDrawable();
}
然后将代码修改为:
byte[] iconBytes = bmpToByteArray(
drawableToBitmap(getNewDrawable(iv.getDrawable())), true);
果不其然,就不再变化了。
下面附上Demo:想研究的同学参考一下:
http://download.csdn.net/detail/guchuanhang/9119861