对于那些正在寻找完整代码的人,此示例代码在相机预览上绘制了一个小矩形。只需添加表面视图并修改Camera2BasicFragment项目中的onViewCreated函数即可。
public class Camera2BasicFragment extends Fragment
implements View.OnClickListener, ActivityCompat.OnRequestPermissionsResultCallback {
SurfaceView surfaceView;
@Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
view.findViewById(R.id.picture).setOnClickListener(this);
view.findViewById(R.id.info).setOnClickListener(this);
mTextureView = (AutoFitTextureView) view.findViewById(R.id.texture);
surfaceView = (SurfaceView) view.findViewById(R.id.surfaceView);
surfaceView.setZOrderOnTop(true);
SurfaceHolder mHolder = surfaceView.getHolder();
mHolder.setFormat(PixelFormat.TRANSPARENT);
mHolder.addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
Canvas canvas = holder.lockCanvas();
if (canvas == null) {
Log.e(TAG, "Cannot draw onto the canvas as it's null");
} else {
Paint myPaint = new Paint();
myPaint.setColor(Color.rgb(100, 20, 50));
myPaint.setStrokeWidth(10);
myPaint.setStyle(Paint.Style.STROKE);
canvas.drawRect(100, 100, 200, 200, myPaint);
holder.unlockCanvasAndPost(canvas);
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
});
}
并且 fragment_camera2_basic.xml 文件有一个额外的表面视图
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.android.camera2basic.AutoFitTextureView
android:id="@+id/texture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true" />
<SurfaceView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/surfaceView"/>
<FrameLayout
android:id="@+id/control"
android:layout_width="match_parent"
android:layout_height="112dp"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:background="@color/control_background">
<Button
android:id="@+id/picture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="@string/picture" />
<ImageButton
android:id="@+id/info"
android:contentDescription="@string/description_info"
style="@android:style/Widget.Material.Light.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|right"
android:padding="20dp"
android:src="@drawable/ic_action_info" />
</FrameLayout>
</RelativeLayout>