Drawing on Canvas outside the onDraw() method

久未见 提交于 2019-12-05 12:29:48

You mustn't take the reference to the Canvas passed, as it is only valid during the onDraw(Canvas) method call.

I recommend reading http://developer.android.com/guide/topics/graphics/2d-graphics.html#draw-with-canvas thoroughly, the possible ways are explained there quite well:

  1. To the Canvas provided to the onDraw(Canvas) method, during this method call. This is done in the UI thread, so nothing complicated should be attempted here
  2. To a Canvas you created yourself. This could be useful for preparing a bitmap in another thread and then drawing the bitmap to the Canvas given to onDraw(Canvas) method
  3. Using a SurfaceView, and obtaining a Canvas object from it with lockCanvas() method.

You can use invalidate(); to call onDraw() and draw canvas depending on your drawing logic.

Example

public class ThumbnailImage extends android.support.v7.widget.AppCompatImageView {

    public static final int FALSE = 0, TRUE = 1, NOT_SET = 2;
    private int drawingStatus;     

    public ThumbnailImage(Context context) {
        super(context);
        init();
    }

    public ThumbnailImage(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public ThumbnailImage(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        ...
        drawingStatus = NOT_SET;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (drawingStatus != NOT_SET) {
            if (drawingStatus == TRUE) {
               ...
            } else {
               ...
            }
        }
    }

    public void setDrawingStatus(int drawingStatus) {
        this.drawingStatus = drawingStatus;
        invalidate();
    }

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