Android - 相机预览
问题描述:
我在尝试相机预览
这是我的代码,它不会引发任何错误,但屏幕仍然是黑色的。任何想法?
This is my code and it doesn't throw any error, but the screen is still black. Any ideas?
this.setContentView(R.layout.camerapreview);
SurfaceView cameraSurface = (SurfaceView)findViewById(R.id.cpPreview);
SurfaceHolder holder = cameraSurface.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
this.camera = Camera.open();
this.camera.setPreviewDisplay(holder);
this.camera.startPreview();
camerapreview.xml
camerapreview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<SurfaceView
android:id="@+id/cpPreview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center">
</SurfaceView>
</LinearLayout>
答
你必须等待表面准备,然后调用 setPreviewDisplay()
,你必须等待表面的大小( surfaceChanged()
),然后调用 startPreview()
。 此项目具有您所需要的。
You are calling the last three lines too early. You have to wait for the surface to be prepared before calling setPreviewDisplay()
and you have to wait for the surface to be sized (surfaceChanged()
) before calling startPreview()
. This project has what you need.