我发现了许多与我的问题相关的帖子,但没有一个解决它。我再试一次。希望我的例子很简单,我没有忘记任何重要的事情。
我有一个Fragment
和一个内部类CameraPreview
,派生自SurfaceView
并实施SurfaceHolder.Callback
。我想要实现的是绘制在CameraPreview
全屏显示的相机预览之上。
我认为在canvas = holder.lockCanvas()
中调用surfaceCreated()
会给我一个Canvas
以供稍后绘制,但如果在mCanvas
和{{之后调用null
,则setPreviewDisplay()
始终为startPreview()
1}}。如果尝试在这两个调用之前创建画布,我会得到一个画布,但应用程序会立即崩溃。
有人可以解释原因吗?
public class CameraFragment extends Fragment {
final static String TAG = "CameraFragment";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_native_camera, container, false);
// Create our Preview view and set it as the content of our activity.
safeCameraOpenInView(view);
return view;
}
public void safeCameraOpenInView(View view) {
FrameLayout preview;
Camera camera = null;
try {
camera = Camera.open();
} catch (Exception e) {
e.printStackTrace();
}
if (camera != null) {
mPreview = new CameraPreview(getActivity().getApplicationContext(), camera);
if (view.findViewById(R.id.camera_preview) != null) {
preview = (FrameLayout) view.findViewById(R.id.camera_preview);
preview.addView(mPreview);
Log.d(TAG, "view found and set");
} else Log.d(TAG, "FrameLayout is null");
}
}
class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private Camera mCamera;
private Canvas mCanvas;
public CameraPreview(Context context, Camera camera) {
super(context);
// not sure the following is necessary
setWillNotDraw(false);
// do camera initialisation etc.
mCamera = camera;
// ...
}
public void surfaceCreated(SurfaceHolder holder) {
// here's the problem: If I initialize the canvas
// before setting the preview display and start previewing
// I get a canvas but the app crashes immediately after
// If I request the canvas afterwards it's simply null
mCamera.setPreviewDisplay(holder);
mCamera.startpreview();
mCanvas = holder.lockCanvas();
// mCanvas is null
Log.d(TAG, "canvas: " + mCanvas);
}
}
}