View组件显示的内容可以通过cache机制保存为bitmap, 使用到的api有
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)实现。
eg.
public class ReflectTextView extends TextView {
public ReflectTextView(Context context) {
super(context);
}
public ReflectTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public ReflectTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onDraw(Canvas canvas) {
//draw the text from layout()
super.onDraw(canvas);
int height = getHeight();
int width = getWidth();
//make the shadow reverse of Y
Matrix matrix = new Matrix();
matrix.preScale(1, -1);
//make sure you can use the cache
setDrawingCacheEnabled(true);
//create bitmap from cache,this is the most important of this
Bitmap originalImage = Bitmap.createBitmap(getDrawingCache());
//create the shadow
Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0,
height / 3, width, height / 3, matrix, false);
//draw the shadow
canvas.drawBitmap(reflectionImage, 0, 8 * height / 12, null);
//process shadow bitmap to make it shadow like
Paint paint = new Paint();
LinearGradient shader = new LinearGradient(0, 8 * height / 12, 0,
height, 0x70ffffff, 0x00ffffff, TileMode.CLAMP);
paint.setShader(shader);
paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
canvas.drawRect(0, 8 * height / 12, width, height, paint);
}
}