gpt4 book ai didi

java - CameraX PreviewView 不显示任何内容

转载 作者:行者123 更新时间:2023-12-02 08:47:36 28 4
gpt4 key购买 nike

我遵循了这些教程: https://developer.android.com/training/camerax/preview , https://proandroiddev.com/update-android-camerax-4a44c3e4cdcc我第一次运行应用程序时,预览工作正常,但在我旋转屏幕后,一切都坏了。我重新安装了应用程序,但预览不再起作用

public class ScanActivity extends AppCompatActivity {


private ListenableFuture<ProcessCameraProvider> cameraProviderFuture;

private PreviewView cameraView;
private Preview imagePreview;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
cameraView = findViewById(R.id.cameraView);
cameraProviderFuture = ProcessCameraProvider.getInstance(this);
if(isPermissionsGranted()){
cameraView.post(new Runnable() {
@Override
public void run() {
startCamera();
}
});
}
else{
ActivityCompat.requestPermissions(ScanActivity.this,
new String[]{Manifest.permission.CAMERA},PERMISSION_REQUEST_CODE);
}
}

private void startCamera(){
imagePreview = new Preview.Builder()
.setTargetRotation(cameraView.getDisplay().getRotation())
.build();
imagePreview.setSurfaceProvider(cameraView.getPreviewSurfaceProvider());
final CameraSelector cameraSelector = new CameraSelector.Builder()
.requireLensFacing(CameraSelector.LENS_FACING_BACK)
.build();
cameraProviderFuture.addListener(() -> {
try {
ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
cameraProvider.bindToLifecycle(ScanActivity.this,cameraSelector,imagePreview);
} catch (ExecutionException|InterruptedException e) {
e.printStackTrace();
}
},ContextCompat.getMainExecutor(this));

}

}

最佳答案

在相机初始化之前不应构建用例,这是 ProcessCameraProvider.getInstance() 异步执行的操作。因此,您可能会遇到的是在初始化完成之前构建预览用例,这就是预览不起作用的原因。您的代码应该如下所示。

cameraProviderFuture.addListener(() -> {
try {
ProcessCameraProvider cameraProvider = cameraProviderFuture.get(context);
Preview preview = new Preview.Builder().build();
preview.setSurfaceProvider(previewView.getSurfaceProvider());
cameraProvider.bindToLifecycle(lifecycleOwner, selector, preview);
} catch (Exception exception) {
exception.printStackTrace();
}
}, ContextCompat.getMainExecutor(context));

关于java - CameraX PreviewView 不显示任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60978235/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com