理解:在安卓中我们根据API可以对VIEW产生其图像缓存
代码演示:
View组件显示的内容可以通过cache机制保存为bitmap,主要有以下方法:
代码演示:
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
TextView textView;
RelativeLayout rl;
ImageView iv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.textView1);
rl = (RelativeLayout)findViewById(R.id.rl);
iv = (ImageView)findViewById(R.id.iv);
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
textView.destroyDrawingCache();
textView.setDrawingCacheEnabled(true);
Bitmap bp = textView.getDrawingCache();
Bitmap cache = Bitmap.createBitmap(bp);//复制bp
textView.setDrawingCacheEnabled(false);//销毁bp
iv.setImageBitmap(cache);//使用复制的bp 也就是cache
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
View组件显示的内容可以通过cache机制保存为bitmap,主要有以下方法:
void setDrawingCacheEnabled(booleanflag),
Bitmap getDrawingCache(booleanautoScale),
void buildDrawingCache(booleanautoScale),
void destroyDrawingCache()
我们要获取cache首先要通过setDrawingCacheEnable方法开启cache,然后再调用getDrawingCache方法就可以获得view的cache图片了。
buildDrawingCache方法可以不用调用,因为调用getDrawingCache方法时,若果cache没有建立,系统会自动调用buildDrawingCache方法生成cache。
若想更新cache,必须要调用destoryDrawingCache方法把旧的cache销毁,才能建立新的。
当调用setDrawingCacheEnabled方法设置为false,系统也会自动把原来的cache销毁。
另外,ViewGroup在绘制子view时,也提供了两个方法
voidsetChildrenDrawingCacheE nabled(booleanenabled)
setChildrenDrawnWithCach eEnabled(booleanenabled)
setChildrenDrawingCacheE nabled方法可以使viewgroup里所有的子view开启cache;
setChildrenDrawnWithCach eEnabled使在绘制子view时,若该子view开启了cache,则使用它的cache进行绘制,从而节省绘制时间。
获取cache通常会占用一定的内存,所以通常不需要的时候有必要对其进行清理,通过destroyDrawingCache或setDrawingCacheEnabled(false)实现。
参考文章:http://blog.sina.com.cn/s/blog_4b93170a0102e40m.html
参考文章:http://blog.sina.com.cn/s/blog_4b93170a0102e40m.html