我通过叠加两个视图(下面称为预览和叠加)来做到这一点。一个负责相机预览,另一个控制画布以绘制我想要的任何东西。
在res/layout/main.xml
:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<FrameLayout
android:id="@+id/toplevelframe"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<your.project.Preview
android:id="@+id/preview"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<your.project.Overlay
android:id="@+id/overlay"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</FrameLayout>
</LinearLayout>
在您的活动课程中,onCreate()
:
...
setContentView(R.layout.main);
mPreview = (Preview) findViewById(R.id.preview);
mOverlay = (Overlay) findViewById(R.id.overlay);
...
在onResume()
:
...
mCamera = Camera.open();
mPreview.setCamera(mCamera);
...
在onPause()
:
if (mCamera != null) {
mPreview.setCamera(null);
mCamera.release();
mCamera = null;
}
类Overlay
扩展 View 并在画布上绘图。没有什么特别的,只是覆盖onDraw()
。
对于相机预览类(Preview
如下),请查看官方指南以获取示例。它看起来像这样:
class Preview extends ViewGroup implements SurfaceHolder.Callback {
...
private SurfaceView mSurfaceView;
private SurfaceHolder mHolder;
private Camera mCamera;
...
public Preview(Context context, AttributeSet aset) {
...
mSurfaceView = new SurfaceView(context);
addView(mSurfaceView);
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = mSurfaceView.getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
...
public void setCamera(Camera camera) {
mCamera = camera;
if (mCamera != null) {
mSupportedPreviewSizes = mCamera.getParameters().getSupportedPreviewSizes();
requestLayout();
}
}
...
}
然后也实现SurfaceHolder.Callback的所有方法。