如何在 Android 上的 Camera 使用的 SurfaceView 上绘制叠加层? [英] How to draw an overlay on a SurfaceView used by Camera on Android?
问题描述
我有一个简单的程序,可以将 Camera
的预览绘制到 SurfaceView
中.我正在尝试使用 onPreviewFrame
方法,每次将新框架绘制到 SurfaceView
时都会调用该方法,以执行 invalidate
方法应该调用 onDraw
方法.实际上,正在调用 onDraw
方法,但没有打印任何内容(我猜相机预览正在覆盖我正在尝试绘制的文本).
I have a simple program that draws the preview of the Camera
into a SurfaceView
. What I'm trying to do is using the onPreviewFrame
method, which is invoked each time a new frame is drawn into the SurfaceView
, in order to execute the invalidate
method which is supposed to invoke the onDraw
method. In fact, the onDraw
method is being invoked, but nothing there is being printed (I guess the camera preview is overwriting the text I'm trying to draw).
这是我拥有的 SurfaceView
子类的简化版本:
This is a simplify version of the SurfaceView
subclass I have:
public class Superficie extends SurfaceView implements SurfaceHolder.Callback {
SurfaceHolder mHolder;
public Camera camera;
Superficie(Context context) {
super(context);
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(final SurfaceHolder holder) {
camera = Camera.open();
try {
camera.setPreviewDisplay(holder);
camera.setPreviewCallback(new PreviewCallback() {
public void onPreviewFrame(byte[] data, Camera arg1) {
invalidar();
}
});
} catch (IOException e) {}
}
public void invalidar(){
invalidate();
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
Camera.Parameters parameters = camera.getParameters();
parameters.setPreviewSize(w, h);
camera.setParameters(parameters);
camera.startPreview();
}
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
// nothing gets drawn :(
Paint p = new Paint(Color.RED);
canvas.drawText("PREVIEW", canvas.getWidth() / 2,
canvas.getHeight() / 2, p);
}
}
推荐答案
SurfaceView
在这方面可能不像普通的View
.
SurfaceView
probably does not work like a regular View
in this regard.
相反,请执行以下操作:
Instead, do the following:
- 把你的
SurfaceView
放在一个FrameLayout
或RelativeLayout
中您的布局 XML 文件,因为两者那些允许堆叠小部件Z轴 - 移动您的绘图逻辑进入一个单独的自定义
View
类 - 添加自定义视图的实例类到布局 XML 文件作为
FrameLayout
的子级或RelativeLayout
,但让它出现SurfaceView
之后
- Put your
SurfaceView
inside of aFrameLayout
orRelativeLayout
in your layout XML file, since both of those allow stacking of widgets on the Z-axis - Move your drawing logic
into a separate custom
View
class - Add an instance of the custom View
class to the layout XML file as a
child of the
FrameLayout
orRelativeLayout
, but have it appear after theSurfaceView
这将使您的自定义 View
类看起来浮在 SurfaceView
上方.
This will cause your custom View
class to appear to float above the SurfaceView
.
这篇关于如何在 Android 上的 Camera 使用的 SurfaceView 上绘制叠加层?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!