static final int REQUEST_IMAGE_CAPTURE = 1; private void dispatchTakePictureIntent() { Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); try { startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE); } catch (ActivityNotFoundException e) { // display error state to the user } }怎么用SurfaceView预览
时间: 2024-02-07 17:03:34 浏览: 160
Android开发之拍照功能实现(附源码)
要使用SurfaceView预览相机画面,可以通过Camera API获取相机实例,并在SurfaceView上绘制预览画面。以下是示例代码:
1. 在布局文件中添加SurfaceView
```
<SurfaceView
android:id="@+id/surfaceView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
2. 在Activity中获取SurfaceView实例,并在SurfaceView的生命周期方法中处理相机预览
```
public class CameraPreviewActivity extends AppCompatActivity implements SurfaceHolder.Callback {
private Camera mCamera;
private SurfaceView mSurfaceView;
private SurfaceHolder mHolder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera_preview);
mSurfaceView = findViewById(R.id.surfaceView);
mHolder = mSurfaceView.getHolder();
mHolder.addCallback(this);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
// 获取相机实例
mCamera = Camera.open();
try {
// 设置预览显示
mCamera.setPreviewDisplay(holder);
// 启动预览
mCamera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// 相机预览尺寸发生变化时,重新启动预览
mCamera.stopPreview();
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// 释放相机资源
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
}
```
在以上代码中,我们通过SurfaceHolder.Callback接口监听SurfaceView的生命周期方法,并在surfaceCreated方法中获取Camera实例、设置预览显示、启动预览,在surfaceChanged方法中处理预览尺寸变化,在surfaceDestroyed方法中释放相机资源。
需要注意的是,为了保证顺利运行,需要在AndroidManifest.xml文件中添加相应的权限:
```
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
```
阅读全文