您好,登錄后才能下訂單哦!
怎樣進行Android CameraX打開攝像頭預覽,相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
目標很簡單,用CameraX打開攝像頭預覽,實時顯示在界面上。看看CameraX有沒有Google說的那么好用。先按最簡單的來,把預覽顯示出來。
模塊gradle的一些配置,使用的Android SDK版本為31,啟用了databinding
apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' apply plugin: 'kotlin-kapt' android { compileSdkVersion 31 buildToolsVersion "31.0.0" defaultConfig { minSdkVersion 21 targetSdkVersion 31 } dataBinding { enabled = true } }
引入CameraX依賴(CameraX 核心庫是用camera2實現的),目前主要用1.1.0-alpha11版本
dependencies { implementation "androidx.camera:camera-core:1.1.0-alpha11" implementation "androidx.camera:camera-camera2:1.1.0-alpha11" implementation "androidx.camera:camera-lifecycle:1.1.0-alpha11" implementation "androidx.camera:camera-view:1.0.0-alpha31" implementation "androidx.camera:camera-extensions:1.0.0-alpha31" }
使用1.0.2版本的CameraX核心庫會報錯,找不到getOrCreateInstance
方法。
??? bug "NoSuchMethodError getOrCreateInstance"
```log CrashHandler: In thread: Thread[main,5,main] UncaughtException detected: java.lang.NoSuchMethodError: No static method getOrCreateInstance(Landroid/content/Context;)Lcom/google/common/util/concurrent/ListenableFuture; in class Landroidx/camera/core/CameraX; or its super classes (declaration of 'androidx.camera.core.CameraX' appears in /data/app/com.rustfisher.tutorial2020-1/base.apk) at androidx.camera.lifecycle.ProcessCameraProvider.getInstance(ProcessCameraProvider.java:149) at com.rustfisher.tutorial2020.camera.SimplePreviewXAct.onCreate(SimplePreviewXAct.java:36) at android.app.Activity.performCreate(Activity.java:6161) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1112) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2507) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2640) at android.app.ActivityThread.access$800(ActivityThread.java:182) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1493) at android.os.Handler.dispatchMessage(Handler.java:111) at android.os.Looper.loop(Looper.java:194) at android.app.ActivityThread.main(ActivityThread.java:5682) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:963) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:758) ```
需要動態申請android.permission.CAMERA
權限
<uses-permission android:name="android.permission.CAMERA" />
本文略過動態申請權限的地方
CameraX為開發者貼心地準備了androidx.camera.view.PreviewView
把它放在一個FrameLayout里,如下的act_simple_preivew_x.layout
<?xml version="1.0" encoding="utf-8"?> <layout> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent"> <androidx.camera.view.PreviewView android:id="@+id/previewView" android:layout_width="match_parent" android:layout_height="match_parent" /> </FrameLayout> </layout>
在activity中開啟相機預覽
// SimplePreviewXAct.java import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.camera.core.Camera; import androidx.camera.core.CameraSelector; import androidx.camera.core.Preview; import androidx.camera.lifecycle.ProcessCameraProvider; import androidx.core.content.ContextCompat; import androidx.databinding.DataBindingUtil; import androidx.lifecycle.LifecycleOwner; import com.google.common.util.concurrent.ListenableFuture; // import com.rustfisher.tutorial2020.R; // import com.rustfisher.tutorial2020.databinding.ActSimplePreivewXBinding; import java.util.concurrent.ExecutionException; public class SimplePreviewXAct extends AppCompatActivity { private ActSimplePreivewXBinding mBinding; private ListenableFuture<ProcessCameraProvider> cameraProviderFuture; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mBinding = DataBindingUtil.setContentView(this, R.layout.act_simple_preivew_x); cameraProviderFuture = ProcessCameraProvider.getInstance(this); cameraProviderFuture.addListener(() -> { try { ProcessCameraProvider cameraProvider = cameraProviderFuture.get(); bindPreview(cameraProvider); } catch (ExecutionException | InterruptedException e) { // 這里不用處理 } }, ContextCompat.getMainExecutor(this)); } void bindPreview(@NonNull ProcessCameraProvider cameraProvider) { Preview preview = new Preview.Builder().build(); CameraSelector cameraSelector = new CameraSelector.Builder() .requireLensFacing(CameraSelector.LENS_FACING_BACK) .build(); preview.setSurfaceProvider(mBinding.previewView.getSurfaceProvider()); Camera camera = cameraProvider.bindToLifecycle(this, cameraSelector, preview); } }
注意我們這里使用的是androidx.appcompat.app.AppCompatActivity
為了獲得ProcessCameraProvider,用ProcessCameraProvider.getInstance
方法拿到一個cameraProviderFuture
。
在cameraProviderFuture
完成后取出ProcessCameraProvider(cameraProvider
)。
要開啟預覽,通過Preview.Builder
構建一個Preview。用CameraSelector來選擇后置攝像頭。
Preview的SurfaceProvider由layout中的androidx.camera.view.PreviewView提供。
cameraProvider.bindToLifecycle
綁定上后,啟動攝像頭預覽
運行到手機上,打開這個Activity就可以看到攝像頭預覽。圖像寬高比正常,沒有拉伸現象。
榮耀 EMUI 3.1 Lite,Android 5.1 運行正常
Redmi 9A,MIUI 12.5.1穩定版,Android 10 運行正常
一加5,H2OS 10.0.3,Android 10 運行正常
在layout里加2個按鈕,控制相機開關
<?xml version="1.0" encoding="utf-8"?> <layout> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/colorPrimaryDark" android:gravity="center" android:orientation="horizontal" android:padding="4dp"> <Button android:id="@+id/start" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="打開" /> <Button android:id="@+id/end" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="12dp" android:text="關閉" /> </LinearLayout> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent"> <androidx.camera.view.PreviewView android:id="@+id/previewView" android:layout_width="match_parent" android:layout_height="match_parent" /> </FrameLayout> </LinearLayout> </layout>
根layout換成LinearLayout
修改bindPreview
方法,先檢查傳入的ProcessCameraProvider是否為空
private void bindPreview(ProcessCameraProvider cameraProvider) { if (cameraProvider == null) { Toast.makeText(getApplicationContext(), "沒獲取到相機", Toast.LENGTH_SHORT).show(); return; } Preview preview = new Preview.Builder().build(); CameraSelector cameraSelector = new CameraSelector.Builder() .requireLensFacing(CameraSelector.LENS_FACING_BACK) .build(); preview.setSurfaceProvider(mBinding.previewView.getSurfaceProvider()); Camera camera = cameraProvider.bindToLifecycle(this, cameraSelector, preview); }
修改后的activity部分代碼
import android.os.Bundle; import android.widget.Toast; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.camera.core.Camera; import androidx.camera.core.CameraSelector; import androidx.camera.core.Preview; import androidx.camera.lifecycle.ProcessCameraProvider; import androidx.core.content.ContextCompat; import androidx.databinding.DataBindingUtil; import com.google.common.util.concurrent.ListenableFuture; // import com.rustfisher.tutorial2020.R; // import com.rustfisher.tutorial2020.databinding.ActSimplePreivewXBinding; import java.util.concurrent.ExecutionException; public class SimplePreviewXAct extends AppCompatActivity { private ActSimplePreivewXBinding mBinding; private ListenableFuture<ProcessCameraProvider> mCameraProviderFuture; private ProcessCameraProvider mCameraProvider; private boolean mRunning = false; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mBinding = DataBindingUtil.setContentView(this, R.layout.act_simple_preivew_x); mCameraProviderFuture = ProcessCameraProvider.getInstance(this); mCameraProviderFuture.addListener(() -> { try { mCameraProvider = mCameraProviderFuture.get(); } catch (ExecutionException | InterruptedException e) { // 這里不用處理 } }, ContextCompat.getMainExecutor(this)); mBinding.start.setOnClickListener(v -> { if (mCameraProvider != null && !mRunning) { bindPreview(mCameraProvider); } }); mBinding.end.setOnClickListener(v -> { mCameraProvider.unbindAll(); mRunning = false; }); } private void bindPreview(ProcessCameraProvider cameraProvider) { if (cameraProvider == null) { Toast.makeText(getApplicationContext(), "沒獲取到相機", Toast.LENGTH_SHORT).show(); return; } Preview preview = new Preview.Builder().build(); CameraSelector cameraSelector = new CameraSelector.Builder() .requireLensFacing(CameraSelector.LENS_FACING_BACK) .build(); preview.setSurfaceProvider(mBinding.previewView.getSurfaceProvider()); Camera camera = cameraProvider.bindToLifecycle(this, cameraSelector, preview); mRunning = true; } }
拿到mCameraProvider
后不要立刻綁定生命周期。
如果要開啟預覽,則調用bindPreview(mCameraProvider)
。記錄一下現在相機已經開啟預覽mRunning = true
。
如果要停止預覽,則解綁生命周期mCameraProvider.unbindAll()
。這個方法需要在主線程調用。
運行起來后,可以用按鈕來控制相機預覽的開關。相比之前,PreviewView的高度變小了一點(讓了點位置給按鈕)。
但視頻寬高比例正常,沒有被拉伸。默認的配置下,還有自動對焦的功能。
從簡單的打開相機預覽來看,CameraX簡化了開發者的工作。提供了PreviewView,開發者不需要自定義SurfaceView或者TextureView。實時預覽中,相機能夠自動對焦。
看完上述內容,你們掌握怎樣進行Android CameraX打開攝像頭預覽的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。