Android Compose中使用CameraX拍摄照片

感谢BitCoder老师的视频讲解
1、在build.gradle中引入CameraX的文件库和权限库

  //相机和照片
    def camerax_version="1.2.0-alpha02"
    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-view:$camerax_version")

    //权限请求
    implementation("com.google.accompanist:accompanist-permissions:0.24.12-rc")
  //加载网络图片
    implementation("io.coil-kt:coil-compose:2.1.0")

2、在res的layout中创建camer_layout.xml文件


<androidx.camera.view.PreviewView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/preview_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

androidx.camera.view.PreviewView>

3、在AndroidManifest.xml中设置相机权限

    <!--    相机-->
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-feature android:name="android.hardware.camera"/>
    <uses-feature android:name="android.hardware.camera.any"/>

4、demo代码:

package com.example.androidcomposetest.widget


import android.Manifest
import android.content.Context
import android.net.Uri
import android.os.Environment
import android.util.Log
import android.widget.Toast
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCaptureException
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import andro

你可能感兴趣的:(笔记,android,kotlin,开发语言)