相機預覽

      在〈相機預覽〉中尚無留言

相機的設定超級複雜,但只要記得如下幾點即可。 cameraProviderFuture(相機提供者監聽器)綁定生命周期時,把 preview 加入 useCaseGroup,再將 useCaseGroup 綁定生命周期,即可預覽。

專案設定

先開啟一個新的Empty Activity 專案,然後於build.gradle新增 CameraX 相依性設定如下

dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.3.2'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
// CameraX core library using the camera2 implementation def camerax_version = "1.2.1" implementation "androidx.camera:camera-core:${camerax_version}" implementation "androidx.camera:camera-camera2:${camerax_version}" implementation "androidx.camera:camera-lifecycle:${camerax_version}" implementation "androidx.camera:camera-video:${camerax_version}" implementation "androidx.camera:camera-view:${camerax_version}" implementation "androidx.camera:camera-extensions:${camerax_version}" }

AndroidManifest.xml新增如下權限

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.asuscomm.mahaljsp.cameraxtest">
<uses-feature android:name="android.hardware.camera.any" />
<uses-permission android:name="android.permission.CAMERA" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.AppCompat.Light.NoActionBar">
<activity android:name=".MainActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

activity_main Layout

在UI的設計中,使用 ConstraintLayout,此Layout允許元件可以重疊。預覽的部份使用CameraX的PreviewView元件。

🔒 更多內容,請登入會員繼續閱讀。

立即登入

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *