getDrawingCache is not updated

核能气质少年 提交于 2019-12-07 10:05:31

问题


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;
}


来源:https://stackoverflow.com/questions/11055133/getdrawingcache-is-not-updated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!