getDrawingCache is not updated

2019-05-07 00:08发布

问题:

I'm calling getDrawingCache in the onDraw function. The problem is that it contains the changes to the canvas only in the first time, and after that, it's not updated at all with the new changes. Here's my code:

        paintAction.draw(canvas);
        if (paintAction.isPermanentChange())
        {
            Bitmap partialBitmap=getDrawingCache();
            int numColored=0;
            for (int index1=0;index1<partialBitmap.getWidth();index1++)
            {
                for (int index2=0;index2<partialBitmap.getHeight();index2++)
                {
                    if (partialBitmap.getPixel(index1,index2)==0xFF000000) 
                        numColored++;
                }
            }
            Log.i("PaintDroid","Bitmap pixels: " + numColored);
            int areaWidth=partialBitmap.getWidth()-SCROLLBAR_SIZE;
            int areaHeight=partialBitmap.getHeight()-SCROLLBAR_SIZE;
            int[] pixels=new int[areaWidth*areaHeight];
            partialBitmap.getPixels(pixels,0,areaWidth,0,0,areaWidth,
                    areaHeight);    
            numColored=0;
            for (int index=0;index<pixels.length;index++)
                if (pixels[index]==0xFF000000) numColored++;
            Log.i("PaintDroid","Pixels: " + numColored);

(setDrawingCache(true) is called when the view is created, because if I call it from onDraw, getDrawingCache will return null.)

As can be seen, I'm counting the number of black pixels, both by traversing the bitmap and getting the values in an array, and as I said, I get the number I expected for in the first time, but after that, it was supposed to increase, yet doesn't change at all!

Does anybody have an idea what's wrong? Thanks.

回答1:

I solved it. The problem was that I called setDrawingCacheEnabled(true) before the last draw operation on the canvas in onDraw. It must be called after you finished drawing, otherwise you won't get correct results.



回答2:

Just to clarify, the problem here is that the View's drawing cache was not invalidated before the second time you call getDrawingCache().

In order for the drawing cache to be refreshed it must be invalidated and the order of call to the methods should be as follows:

public Bitmap renderView(View view) {
    view.setDrawingCacheEnabled(true)
    Bitmap bitmap = view.getDrawingCache();
    view.setDrawingCacheEnabled(false)
    return bitmap;
}