如何从SurfaceView绘制到Canvas? [英] How to draw to Canvas from SurfaceView?
问题描述
我正在尝试做简单的画家。好像Android有三个独立的Canvas的问题,给我它可以按顺序绘制。
I'm trying to do simple painter. The problem that it looks like Android has three independent Canvas and give me it for drawing sequentially.
我使用 SurfaceView
制作了UI,从其中获得了Holder。
I made UI with SurfaceView
, took Holder from it.
@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。
Then took 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;
}
截屏视频:
出什么问题了?
推荐答案
Canvas $
Surface.lockCanvas
给您的c $ c 不是持久性的。调用 unlockCanvasAndPost
的那一刻,表面缓冲区的内容被推送到屏幕上。每次调用 lockCanvas
时,都需要从头开始重新绘制图片。
The Canvas
that Surface.lockCanvas
gives you is not persistent. The moment you call unlockCanvasAndPost
, the contents of the surface buffer are pushed out to the screen. Every time you call lockCanvas
you need to redraw the picture from scratch.
如果要增量更新画布,则应保持屏幕外 由位图
支持的画布,您可以根据用户操作对其进行更新。然后将位图绘制到 Surface
画布上。
If you want to update the canvas incrementally, you should keep an "off-screen" canvas backed by a Bitmap
that you update in response to user actions. Then paint the bitmap to the Surface
canvas.
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()
表示需要重新绘制。
I'm not sure if you really need a SurfaceView
. You could just extend the View
and override its View.onDraw
method. In that case, call view.invalidate()
to indicate it needs to be redrawn.
另请参见:< a href = https://stackoverflow.com/questions/2423327/android-view-ondraw-always-has-a-clean-canvas> Android View.onDraw()始终具有干净的画布
这篇关于如何从SurfaceView绘制到Canvas?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!