首页 > 系统 > Android > 正文

Android 如何保存某个布局为图片

2019-11-09 18:25:40
字体:
来源:转载
供稿:网友

主要以下代码,得到某个布局或者某个控件后在子纯种中执行: (当view的visibility=”invisible”也有效)

view.setDrawingCacheEnabled(true);view.buildDrawingCache();Bitmap bmp = view.getDrawingCache(); // 子线程中获取Bitmap

代码如下:

package com.cyy.wifidemo;/** * @author chenyingyou * */public class MainActivity extends Activity { PRivate Handler mHandler = new Handler(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main1); initView(); } private void initView() { // 获取图片某布局 final View view = findViewById(R.id.id_ll); view.setDrawingCacheEnabled(true); view.buildDrawingCache(); mHandler.postDelayed(new Runnable() { @Override public void run() { // 要在运行在子线程中 final Bitmap bmp = view.getDrawingCache(); // 获取图片 savePicture(bmp, "test.jpg");// 保存图片 view.destroyDrawingCache(); // 保存过后释放资源 } }, 5000); } public void savePicture(Bitmap bm, String fileName) { if (bm == null) { Toast.makeText(this, "savePicture null !", Toast.LENGTH_SHORT).show(); return; } File foder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/test"); if (!foder.exists()) { foder.mkdirs(); } File myCaptureFile = new File(foder, fileName); try { if (!myCaptureFile.exists()) { myCaptureFile.createNewFile(); } BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile)); bm.compress(Bitmap.CompressFormat.JPEG, 90, bos); bos.flush(); bos.close(); } catch (IOException e) { e.printStackTrace(); } Toast.makeText(this, "保存成功!", Toast.LENGTH_SHORT).show(); }}

总结<转>: View组件显示的内容可以通过cache机制保存为bitmap, 主要有以下方法:

void setDrawingCacheEnabled(boolean flag), Bitmap getDrawingCache(boolean autoScale), void buildDrawingCache(boolean autoScale), void destroyDrawingCache() 我们要获取cache首先要通过setDrawingCacheEnable方法开启cache,然后再调用getDrawingCache方法就可以获得view的cache图片了。

buildDrawingCache方法可以不用调用,因为调用getDrawingCache方法时,若果cache没有建立,系统会自动调用buildDrawingCache方法生成cache。

若想更新cache, 必须要调用destoryDrawingCache方法把旧的cache销毁,才能建立新的。

当调用setDrawingCacheEnabled方法设置为false, 系统也会自动把原来的cache销毁。

另外,ViewGroup在绘制子view时,也提供了两个方法

void setChildrenDrawingCacheEnabled(boolean enabled) setChildrenDrawnWithCacheEnabled(boolean enabled)

setChildrenDrawingCacheEnabled方法可以使viewgroup里所有的子view开启cache;

setChildrenDrawnWithCacheEnabled使在绘制子view时,若该子view开启了cache, 则使用它的cache进行绘制,从而节省绘制时间。

获取cache通常会占用一定的内存,所以通常不需要的时候有必要对其进行清理,通过destroyDrawingCache或setDrawingCacheEnabled(false)实现。

还可以用以下方式获取Bitmap

final Bitmap bmp = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.RGB_8888); view.draw(new Canvas(bmp));
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表