我用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;
}
截屏视频:
有什么问题?
答案 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()
表示需要重新绘制。