AndroidView获取CameraPreview的方法
How to get CameraPreview by AndroidView
我在布局资源文件中创建了 CameraPreview,我想通过单击导航图标按钮在 AndroidView 中显示此文件。
// navigation icon button
Icon(
vectorResource(id = R.drawable.ic_photo),
modifier = Modifier.clickable(onClick = /* show CameraPreview */)
)
// compose CameraPreview
@Composable
fun CameraPreview() {
val lifecycleOwner = LifecycleOwnerAmbient.current
val context = ContextAmbient.current
val cameraProviderFuture = remember { ProcessCameraProvider.getInstance(context) }
AndroidView(viewBlock = { ctx ->
/* get the CameraPreview */
})
}
// xml file
<androidx.camera.view.PreviewView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/previewView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
在您的可组合项本身中创建 PreviewView
的实例:
@Composable
fun CameraPreview() {
val lifecycleOwner = LifecycleOwnerAmbient.current
val context = ContextAmbient.current
val cameraProviderFuture = remember { ProcessCameraProvider.getInstance(context) }
val previewView = remember { PreviewView(context) }
AndroidView(viewBlock = { previewView }) {
// Initialize your camera here
}
}
我在布局资源文件中创建了 CameraPreview,我想通过单击导航图标按钮在 AndroidView 中显示此文件。
// navigation icon button
Icon(
vectorResource(id = R.drawable.ic_photo),
modifier = Modifier.clickable(onClick = /* show CameraPreview */)
)
// compose CameraPreview
@Composable
fun CameraPreview() {
val lifecycleOwner = LifecycleOwnerAmbient.current
val context = ContextAmbient.current
val cameraProviderFuture = remember { ProcessCameraProvider.getInstance(context) }
AndroidView(viewBlock = { ctx ->
/* get the CameraPreview */
})
}
// xml file
<androidx.camera.view.PreviewView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/previewView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
在您的可组合项本身中创建 PreviewView
的实例:
@Composable
fun CameraPreview() {
val lifecycleOwner = LifecycleOwnerAmbient.current
val context = ContextAmbient.current
val cameraProviderFuture = remember { ProcessCameraProvider.getInstance(context) }
val previewView = remember { PreviewView(context) }
AndroidView(viewBlock = { previewView }) {
// Initialize your camera here
}
}