Saving Canvas in onDraw();

≡放荡痞女 提交于 2019-12-10 23:36:37

问题


I'm trying to save the Canvas object in a onDraw() method. This is because i'm using a foreach loop in the onDraw method resulting in : canvas.DrawText (textitem , x,y, textpaint);
(i have to do this because im drawing the text around a masked area)

what im trying now is this :

@Override
public void onDraw(Canvas canvas)
{
if (hasrun = false)
        {
            for(CustomTextViewDrawItem item : drawItemList)
            {
                canvas.drawText(item.Text, item.X, item.Y, textPaint);
            }

            if (eLabel.backgroundGradient != null)
            {
                canvas.drawPath(path, fillPaint);
            }
            canvas.save();
            savedCanvas = canvas ;
        }
        else 
        {
            canvas = savedCanvas; 
        }

        hasrun = true; 
        super.onDraw(canvas);
}

when debugging I see it looks ok, but comes out empty . what would be the best way to get this working ?


回答1:


Maybe that is because of this:

if (hasrun = false)

I guess you intend to do this instead:

if (hasrun == false)



回答2:


You can try to save the bitmap: (I think it is better to call the super.onDraw(canvas); at the start on the method, because your view related drawing will be on top)


@Override
public void onDraw(Canvas canvas)
{
        super.onDraw(canvas);
        if (savedBitmap==null){
            savedBitmap = Bitmap.createBitmap(canvas.getWidth(), canvas.getHeight(), Config.ARGB_8888);
            Canvas canvasToSave = new Canvas(savedBitmap)
            for(CustomTextViewDrawItem item : drawItemList){
                canvasToSave.drawText(item.Text, item.X, item.Y, textPaint);
            }

            if (eLabel.backgroundGradient != null){
                canvasToSave.drawPath(path, fillPaint);
            }
        }
        canvas.drawBitmap(savedBitmap, 0, 0, new Paint());
}



来源:https://stackoverflow.com/questions/7441925/saving-canvas-in-ondraw

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