Android 用用 camera2 API 自定义相机自定义相机
前言前言
笔者因为项目需要自定义相机,所以了解了一下 Android 关于 camera 这块的 API。Android SDK 21(LOLLIPOP) 开始已经弃用了之前的 Camera 类,提供了 camera2 相关
API,目前网上关于 camera2 API 介绍的资料比较少,笔者搜集网上资料,结合自己的实践,在这里做一个总结。
流程流程
因为 camera2 提供的接口比较多,虽然很灵活,但是也增加了使用的复杂度。首先来大致了解一下调用 camera2 的流程,方便我们理清思路。
要显示相机捕捉的画面,只需要三步:初始化相机,预览,更新预览。也就是上图中左侧的部分。要实现这三步,需要用到的主要接口类和它们的作用步骤如上图右侧部分所
示。下面就用代码来详解一下。
案例案例
首先创建一个相机界面:
activity_camera.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextureView
android:id="@+id/camera_texture_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ImageButton
android:id="@+id/capture_ib"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_marginBottom="10dp"
android:layout_gravity="bottom|center"
android:background="@drawable/send_pres"/>
</LinearLayout>
界面很简单,只有一个 TexureView 和一个按钮。
接下来在 Activity 中初始化并显示相机捕捉的画面。
首先要解决的一个问题就是画面拉伸的问题。
要解决这个问题,首先要从 TextureView 下手。
CameraActivity.java
mTextureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) {
mWidth = width;
评论0