在做二维码保存成图片的时候遇到了几个问题。在这里记录一下。也方便一下后来的同学。不足之处请指正~
1.如何将二维码图片(包括布局整个页面保存下来)保存下来?
经过查找资料发现用到的知识点是:将View转化为Bitmap并保存下来有一个方法是使用:View里面有几个方法,
setDrawingCacheEnabled(boolean b);
This API can be used to manually generate a bitmap copy of this view, by setting the flag to true and calling
getDrawingCache();
A non-scaled bitmap representing this view or null if cache is disabled
DestoryDrawingCache();
Frees the resources by the drawing cache,if you can call bulidDrawingCache() or setDrawingCacheEnable(true),you should cleanup the cache with this method afterwards.
大概意思就是:我们可以利用它们把view转化为Bitmap
下面是我写的一个小例子:
public Bitmap convertViewToBitmap() {
TestView.setDrawingCacheEnabled(true);
TestView.measure(
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
Bitmap bitmap = TestView.getDrawingCache();
return bitmap;
}
if(item.getItemId()==R.id.action_save_pic){
Bitmap bitmap = convertViewToBitmap();
getCommand().savePicture(bitmap);
TestView.setDrawingCacheEnabled(false);
TestView.destoryDrawingCache();//这里记得将缓存销毁
}
使用该方法可以将一个布局转化为Bitmap,然后再保存。
*这里我遇到的一个问题就是按照网络上的写法保存了以后布局会乱跑至左上角,一开始参考网络上的写法
网络上大家提供的方法写的是:
contentLayout.setDrawingCacheEnabled(true);
contentLayout.measure(
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
contentLayout.layout(0, 0, contentLayout.getMeasuredWidth(),
contentLayout.getMeasuredHeight());
contentLayout.buildDrawingCache();
Bitmap bitmap= contentLayout.getDrawingCache();
在使用的时候调用
Bitmap bitmap = view.getDrawingCache();
以上是网络上的代码,使用该代码以后会出现跑到右上角的问题,还有就是我之前在这块新new 了一个Bitmap来保存缓存的图片,然后这里设置了 contentLayout.layout(0, 0, contentLayout.getMeasuredWidth(),contentLayout.getMeasuredHeight()); 这样使得布局在左上角显示。
保存的二维码图片一片黑
生成二维码的代码:加上如下判断,意思就是有信息的点显示黑色,无信息的点显示白色。另外保存成png默认背景是黑色的,所以会看到一片黑。
if (resMatrix.get(x, y)) {
pixels[y * width + x] = 0xff000000;//白色
} else {
pixels[y * width + x] = 0xffffffff;//黑色
}
总结:在遇到需要把布局截图保存问题可以使用该方法,自己的理解就是使用了darwingcache以后把View缓存转化为了Bitmap,然后我们可以保存该Bitmap.希望能帮助到大家。