请解释图形缓存在Android中的工作原理。我正在实现一个自定义View子类。我希望系统缓存我的绘图。在View构造函数中,我调用
setDrawingCacheEnabled(true);
然后在绘图(Canvas c)中,我这样做:
Bitmap cac = getDrawingCache();
if(cac != null)
{
c.drawBitmap(cac, 0, 0, new Paint());
return;
}
然而getDrawingCache()
对我返回null。我的draw()
既未来自setDrawingCacheEnabled()
,也未来自getDrawingCache()
。拜托,我做错了什么?
答案 0 :(得分:8)
绘制缓存大小有一个硬性限制,可通过ViewConfiguration类获得。我的视图大于允许缓存。
仅供参考,View类的来源可通过SDK Manager获取,用于某些(并非所有)Android版本。
答案 1 :(得分:6)
希望这可以解释它。
public class YourCustomView extends View {
private String mSomeProperty;
public YourCustomView(Context context) {
super(context);
}
public YourCustomView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public YourCustomView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void setSomeProperty(String value) {
mSomeProperty = value;
setDrawingCacheEnabled(false); // clear the cache here
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// specific draw logic here
setDrawingCacheEnabled(true); // cache
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
...
}
}
解释了示例代码。