Android FingerPaint Example using Canvas, what is

2019-07-24 09:00发布

问题:

Hi I was reading the fingerpaint example, because I'm building a signature activity, that allows the user to draw a signature on the cellphone and then save it to SD.

So far I've seen that the mPath variables holds the path that the user is currently drawing, and this path is drawn onto the screen on the onDraw(..) method by calling

canvas.drawPath(mPath, mPaint);

However on the example there is another canvas "mCanvas" that draws the path on the touch listener:

private void touch_up() {
    mPath.lineTo(mX, mY);
    // commit the path to our offscreen
    mCanvas.drawPath(mPath, mPaint);
    // kill this so we don't double draw
    mPath.reset();
}

And this is what I don't get. what is exactly this mCanvas object, and why are they using it in the example, it seems that only the regular canvas from the onDraw method and the mPath variable would have been enough for doing this?

回答1:

The onDraw method is executed on the UI thread. While we don't have access to the UI thread (you don't want to be using the UI thread that often) we keep an off-screen Bitmap with a Canvas that we use to draw on it.

Why do this? This is because it allows us to focus on the drawing/processing without having to worry about blocking the UI thread.

Note: Calling the method invalidate (or postInvalidate) does not instantaneously block and call onDraw - it just queues up a draw call with the OS.