Android绘图缓存

时间:2010-06-15 15:44:55

标签: android view

请解释图形缓存在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()。拜托,我做错了什么?

2 个答案:

答案 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) {
        ...
    }

}

解释了示例代码。

  1. 在setSomeProperty()方法中调用setDrawingCacheEnabled(false)清除缓存并通过调用invalidate()强制重绘。
  2. 绘制到画布后,在onDraw方法中调用setDrawingCacheEnabled(true)。
  3. 可选择在onDraw方法中放置一个日志语句,以确认每次调用setSomeProperty()方法时只调用一次。请确保在确认后删除日志调用,因为这将成为性能问题。
相关问题