CameraX 是一个 Jetpack 库,旨在帮助您更轻松地开发相机应用。 对于新应用,我们建议从 CameraX 开始。它提供一致且易于使用的 API,适用于绝大多数 Android 设备,并向后兼容 Android 5.0(API 级别 21)。
CameraX 支持大多数常见的相机用例:
预览
:在屏幕上查看图片。图片分析
:无缝访问缓冲区中的图片以便在算法中使用,例如将其传递到机器学习套件。图片拍摄
:保存图片。视频拍摄
:保存视频和音频。
这篇文章讲的是 – 实现预览
在向应用添加预览时,请使用 PreviewView,这是一种可以剪裁、缩放和旋转以确保正确显示的 View。
当相机处于活动状态时,图片预览会流式传输到 PreviewView 中的 Surface。
效果图
配置:
注意:CameraX 支持的最小SDK版本是21
- 一、添加权限
1、清单文件中加入相机权限
<uses-permission android:name="android.permission.CAMERA" />
2、动态获取相机权限
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.CAMERA}, 11);
}
} else {
//启动相机
}
- 二、在build.gradle中 添加CameraX依赖
implementation "androidx.camera:camera-core:1.1.0-alpha10"
// CameraX Camera2 extensions[可选]拓展库可实现人像、HDR、夜间和美颜、滤镜但依赖于OEM
implementation "androidx.camera:camera-camera2:1.1.0-alpha10"
// CameraX Lifecycle library[可选]避免手动在生命周期释放和销毁数据
implementation "androidx.camera:camera-lifecycle:1.1.0-alpha10"
// CameraX View class[可选]最佳实践,最好用里面的PreviewView,它会自行判断用SurfaceView还是TextureView来实现
implementation 'androidx.camera:camera-view:1.0.0-alpha23'
使用 PreviewView案例步骤:
1、(可选)配置 CameraXConfig.Provider。
2、 将 PreviewView 添加到布局。
3、 请求 ProcessCameraProvider。
4、 在创建 View 时,请检查 ProcessCameraProvider。
5、 选择相机并绑定生命周期和用例。
- 将 PreviewView 添加到布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout
android:layout_centerInParent="true"
android:layout_width="500dp"
android:layout_height="500dp">
<androidx.camera.view.PreviewView
android:id="@+id/previewView"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</FrameLayout>
</RelativeLayout>
- 步骤3、4、5、的处理
package com.example.myapplication;
import androidx.annotation.NonNull;
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.camera.view.PreviewView;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.LifecycleOwner;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import com.google.common.util.concurrent.ListenableFuture;
import java.util.concurrent.ExecutionException;
public class MainActivity extends AppCompatActivity {
private ListenableFuture<ProcessCameraProvider> cameraProviderFuture;
private PreviewView previewView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
previewView=findViewById(R.id.previewView);//初始化
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.CAMERA}, 11);
}
} else {
//启动相机
startCamera();
}
}
private void startCamera() {
// 请求 CameraProvider
cameraProviderFuture = ProcessCameraProvider.getInstance(this);
//检查 CameraProvider 可用性,验证它能否在视图创建后成功初始化
cameraProviderFuture.addListener(() -> {
try {
ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
bindPreview(cameraProvider);
} catch (ExecutionException | InterruptedException e) {
// No errors need to be handled for this Future.
// This should never be reached.
}
}, ContextCompat.getMainExecutor(this));
}
//选择相机并绑定生命周期和用例
private void bindPreview(@NonNull ProcessCameraProvider cameraProvider) {
Preview preview = new Preview.Builder()
.build();
CameraSelector cameraSelector = new CameraSelector.Builder()
.requireLensFacing(CameraSelector.LENS_FACING_BACK)
.build();
preview.setSurfaceProvider(previewView.getSurfaceProvider());
Camera camera = cameraProvider.bindToLifecycle((LifecycleOwner)this, cameraSelector, preview);
}
}
- 到bindPreview这一步,相机预览已经显示,请查验
如果是前后翻转
- 解绑每个组件
cameraProvider.unbindAll();
- 布局如下:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:onClick="btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="前置摄像头"
/>
<Button
android:onClick="btn2"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="后置摄像头"
/>
<FrameLayout
android:layout_centerInParent="true"
android:layout_width="500dp"
android:layout_height="500dp">
<androidx.camera.view.PreviewView
android:id="@+id/previewView"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</FrameLayout>
</RelativeLayout>
- 代码详情如下:
public class MainActivity extends AppCompatActivity {
private ListenableFuture<ProcessCameraProvider> cameraProviderFuture;
private PreviewView previewView;
private ProcessCameraProvider cameraProvider;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
previewView=findViewById(R.id.previewView);//初始化
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.CAMERA}, 11);
}
} else {
//启动相机
startCamera(CameraSelector.LENS_FACING_BACK);
}
}
private void startCamera(int state) {
// 请求 CameraProvider
cameraProviderFuture = ProcessCameraProvider.getInstance(this);
//检查 CameraProvider 可用性,验证它能否在视图创建后成功初始化
cameraProviderFuture.addListener(() -> {
try {
ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
bindPreview(cameraProvider,state);
} catch (ExecutionException | InterruptedException e) {
// No errors need to be handled for this Future.
// This should never be reached.
}
}, ContextCompat.getMainExecutor(this));
}
//选择相机并绑定生命周期和用例
private void bindPreview(@NonNull ProcessCameraProvider cp,int state) {
this.cameraProvider=cp;
Preview preview = new Preview.Builder()
.build();
CameraSelector cameraSelector = new CameraSelector.Builder()
.requireLensFacing(state)
.build();
preview.setSurfaceProvider(previewView.getSurfaceProvider());
cameraProvider.unbindAll();//解绑组件
cameraProvider.bindToLifecycle((LifecycleOwner) this, cameraSelector, preview);
}
//点击翻转到前置
public void btn1(View view) {
//启动相机
bindPreview(cameraProvider,CameraSelector.LENS_FACING_FRONT);
}
//点击翻转到后置
public void btn2(View view) {
//启动相机
bindPreview(cameraProvider,CameraSelector.LENS_FACING_BACK);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode==11){//获取权限后,开启摄像头
//启动相机
startCamera(CameraSelector.LENS_FACING_BACK);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
cameraProvider.unbindAll();
}
}