Android: How to draw on a Surfaceview which already is displaying a Camara Preview

本秂侑毒 提交于 2019-12-06 05:07:39

You can't. A Surface is the producer side of a producer-consumer pair, and there can only be one producer at a time. You can provide camera frames, render in software with Canvas, or render in hardware with OpenGL, but you can't mix them up on a single Surface.

You have a few options. One approach is to use a second SurfaceView that overlaps the first (via a FrameLayout). For this to work, you must specify the Z order for the second Surface -- if you don't, the system will see that you have two Surfaces attempting to occupy the same space, and only one will win. Use the setZOrderMediaOverlay() method to place the new Surface in front of the camera preview but behind the View UI. You also need to change the Surface's color format from the default RGB565 to one that supports transparency; setColorFormat(TRANSLUCENT) or RGB8888 will work. Make sure you erase the Surface to transparent black with an appropriate color transfer mode.

Another approach is to use a custom View. This is more efficient, as it doesn't involve creating a separate Surface (you're drawing on the View UI layer), and Canvas rendering can be hardware-accelerated. The most convenient View to use is the one that's part of SurfaceView -- no change to your layout is required. If your code is sub-classing SurfaceView you're halfway there already.

For an example of multiple overlapping SurfaceViews, see Grafika's "multi-surface test" Activity. If you want to understand more about Android's graphics system, see the architecture doc.

If you using a SurfaceView for displaying the Camera preview, you cannot draw to it. lockCanvas will fail as you've seen.

I would suggest that you use two separate views. One SurfaceView that previews the camera, and a second View (either a SurfaceView or just a custom View), that draws over the top of the preview. You can have both views inside of a FrameLayout or a RelativeLayout.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!