有时候在一个应用程序中我们突然发现这个应用程序的View特别好看,我们想把它保存为图片保存在手机上,这时候我们该如何做呢?
在View中可以使用Cache机制将View上的内容保存为Bitmap。
如何获得Cache
我们先看如下几个方法:
void setDrawingCacheEnabled(boolean flag):设置该View可生成Cache.
Bitmap getDrawingCache(boolean autoScale):通过View生成的Cache生成一个Bitmap
void buildDrawingCache(boolean autoScale):自动创建所需要的Cache.
void destroyDrawingCache():销毁所创建的cache。
如何获得View的Cache:
1. 通过setDrawingCacheEnable方法把cache开启。
2. 再调用getDrawingCache方法就可 以获得view的cache图片。
注意:此处不用调用buildDrawingCache方法,因为调用getDrawingCache方法时,若果 cache没有建立,系统会自动调用buildDrawingCache方法生成cache。
3. 如果想要更新Cache,就使用destoryDrawingCache方法把旧的cache销毁,白酒的Cache删除掉,否则获得的是旧的Cache。
代码实现Cache获取
这里使用的是我们在《Android 自定义View——蒙版擦除效果实现(》使用的例子,通过点击按钮后,将每次擦除的蒙版后的View保存为图片。
1. 布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:mybitmapviewanother="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.administrator.mywidgetdemo.activity.PathActivity">
<Button
android:id="@+id/button_save"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<com.example.administrator.mywidgetdemo.bitmap.MyBitmapViewAnother
android:id="@+id/mypicture"
android:layout_width="match_parent"
android:layout_height="match_parent"
mybitmapviewanother:mybitmapviewanother_background="@mipmap/cc"
mybitmapviewanother:mybitmapviewanother_paintwidth="100dp"/>
</LinearLayout>
2. Activity:
public class PathActivity extends Activity {
private Button mButtonSave;//图片保存按钮
private MyBitmapViewAnother myBitmapViewAnother;//自定义的View
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_path);
myBitmapViewAnother = (MyBitmapViewAnother) findViewById(R.id.mypicture);
mButtonSave = (Button) findViewById(R.id.button_save);
//定义点击事件
mButtonSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//将View时候开启Cache设为true
myBitmapViewAnother.setDrawingCacheEnabled(true);
// myBitmapViewAnother.invalidate();//更新画面,否则重复按按钮保存的是统一张图片
//将缓存保存为Bitmap的图片
Bitmap bitmap = myBitmapViewAnother.getDrawingCache();
//设置一个保存的路径,并以时间创建一个图片文件。
File file = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
//经Bitmap保存为图片,保存在File下
try {
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//销毁缓存,当在此点击按钮时建立新的缓存。
myBitmapViewAnother.destroyDrawingCache();
}
});
}
}
看结果,我们通过点击按钮,将View保存为图片,然后再次绘制View,将View保存为新的图片:
我们可以看到,在路径下有两个图片,分别是我们保存的不同时刻绘制不同的图片: