如何从SurfaceView绘制到Canvas?

时间:2016-03-28 17:01:00

标签: android canvas surfaceview

我试图做一个简单的画家。它看起来像Android有三个独立的Canvas的问题,并给我顺序绘图。

我用SurfaceView创建了用户界面,从中获取了持有人。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    sv = (SurfaceView) findViewById(R.id.sv);
    holder = sv.getHolder();

    holder.addCallback(callback);
}

然后拿了Surface。

@Override
    public void surfaceCreated(SurfaceHolder holder) {
    surface = holder.getSurface();
}

来自OnTouchListener()的事件画出点和线。

private void paintStartDot(float x, float y) {
    Canvas canvas = surface.lockCanvas(null);

    canvas.drawPoint(x, y, drawPaint);
    surface.unlockCanvasAndPost(canvas);

    lastX = x;
    lastY = y;
}

private void paintEndDot(float x, float y) {
    Canvas canvas = surface.lockCanvas(null);

    canvas.drawLine(lastX, lastY, x, y, drawPaint);

    surface.unlockCanvasAndPost(canvas);

    lastX = x;
    lastY = y;
}

截屏视频:

https://youtu.be/NNDnzrtMLZI

有什么问题?

此处提供完整资源: https://github.com/tseglevskiy/canvasdemo1/blob/error/app/src/main/java/ru/jollydroid/canvasdemo1/MainActivity.java

1 个答案:

答案 0 :(得分:6)

Canvas为您提供的Surface.lockCanvas 不会持久。当您调用unlockCanvasAndPost时,表面缓冲区的内容将被推送到屏幕。每次拨打lockCanvas时,都需要从头开始重新绘制图片。

如果你想以增量方式更新画布,你应该保持"屏幕外的"您为响应用户操作而更新的canvas backed by a Bitmap。然后将位图绘制到Surface画布。

private void paintStartDot(float x, float y) {
    if (mBitmap == null) return;  // not ready yet
    Canvas canvas = new Canvas(mBitmap);
    canvas.drawPoint(x, y, drawPaint);

    // draw the bitmap to surface 
    canvas = surface.lockCanvas(null);
    canvas.drawBitmap(mBitmap, 0, 0, null);
    surface.unlockCanvasAndPost(canvas);
}

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    // good place to create the Bitmap
    mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config. ARGB_8888);
    // also here we need to transform the old bitmap to new one
}

我不确定你是否真的需要SurfaceView。您可以扩展View并覆盖其View.onDraw方法。在这种情况下,请调用view.invalidate()表示需要重新绘制。

另请参阅:Android View.onDraw() always has a clean Canvas