使用画布和表面视图在 Android 上使用 Java 进行双缓冲

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6538423/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 16:16:03  来源:igfitidea点击:

Double buffering in Java on Android with canvas and surfaceview

javaandroidcanvasdoublebuffered

提问by Kalina

How does one go about doing this? Could somebody give me an outline?

怎么做呢?有人可以给我一个大纲吗?

From what I've found online, it seems like in my run() function:

从我在网上找到的内容来看,它似乎在我的 run() 函数中:

  1. create a bitmap
  2. create a canvas and attach it to the bitmap
  3. lockCanvas()
  4. call draw(canvas) and draw bitmap into back buffer (how??)
  5. unlockCanvasAndPost()
  1. 创建位图
  2. 创建画布并将其附加到位图
  3. 锁画布()
  4. 调用 draw(canvas) 并将位图绘制到后台缓冲区中(如何??)
  5. 解锁CanvasAndPost()

Is this correct? If so, could I get a bit of an explanation; what do these steps mean and how do I implement them? I've never programmed for Android before so I'm a real noob. And if it isn't correct, how DO I do this?

这个对吗?如果是这样,我能得到一些解释吗?这些步骤是什么意思,我该如何实施?我以前从未为 Android 编程,所以我是一个真正的菜鸟。如果它不正确,我该怎么做?

回答by Romain Guy

It's already double buffered, that's what the unlockCanvasAndPost() call does. There is no need to create a bitmap.

它已经是双缓冲的,这就是 unlockCanvasAndPost() 调用所做的。无需创建位图。

回答by Rustem Galiullin

The steps from Android Developers Groupsay that you need a buffer-canvas, to which all the renders are drawn onto.

Android Developers Group的步骤说您需要一个缓冲区画布,所有渲染都被绘制到该画布上。

Bitmap buffCanvasBitmap;
Canvas buffCanvas;

// Creating bitmap with attaching it to the buffer-canvas, it means that all the changes // done with the canvas are captured into the attached bitmap
tempCanvasBitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
tempCanvas = new Canvas();
tempCanvas.setBitmap(tempCanvasBitmap);

// and then you lock main canvas
canvas = getHolder().lockCanvas();              
// draw everything you need into the buffer
tempCanvas.drawRect.... // and etc
// then you draw the attached bitmap into the main canvas
canvas.drawBitmap(tempCanvasBitmap, 0, 0, drawView.getPaint());
// then unlocking canvas to let it be drawn with main mechanisms
getHolder().unlockCanvasAndPost(canvas);

You are getting the main buffer, which you are drawing into without getting different double-buffer canvas' on each holder's lock.

您正在获取主缓冲区,您正在绘制该缓冲区,而不会在每个持有人的锁上获得不同的双缓冲区画布。