close

這次我們要刻一個自訂的相機介面

沒錯,相機的 UI 由我們自己決定

 

我將相機有關的功能包成一個庫

只要匯入控制項的 UI 即可順利的弄出一個相機囉

目前功能只有 拍照、切換鏡頭、開關閃光燈、橫直屏轉換。

有時間的話,預計之後會有濾鏡、圖像辨識…等。

Sample 如下:

device-2020-11-10-185405         device-2020-11-10-185459

 

原碼點此進入:https://github.com/WillysFish/CustomControlsCamera

 

接下來我們就簡單介紹一下怎麼使用吧?

即然是相機,首先我們就要取得 Android 的相機權限吧!!

在 Manifest 加入下列

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

 

然後在洽當的地方 call Activity.requestPermissions()

用來詢問使用者給不給用相機

private const val PERMISSIONS_REQUEST_CODE = 111
private val PERMISSIONS_REQUIRED = a
                rrayOf(Manifest.permission.CAMERA)
requestPermissions(PERMISSIONS_REQUIRED, PERMISSIONS_REQUEST_CODE)

 

然後把我們的 View 加進 Layout 裡面

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <studio.zewei.willy.customcontrolscameraview.CustomControlsCameraView
        android:id="@+id/cameraView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/black" />
</androidx.constraintlayout.widget.ConstraintLayout>

 

最後一步

把我們自己想要的 Controls Layout ID 匯入就可以了

而且也可以取出來做使用

下方就是設定快門的範例

// Init CameraView
cameraView.initCameraWithOwner(this, R.layout.camera_control_layout)

// Wait for the views to be properly laid out
cameraView.postDelayed({
    val controlsView = cameraView.controlsView

    controlsView?.apply {
        captureBtn.setOnClickListener {
            cameraView.capture(getCaptureFile()) {
                // show dialog on ui thread
            }
        }
。。。

 

到這裡我們已經可以拍照了

如果還需要其它的功能

可以點我到 Github 看看

 

Library 使用方法:

在 root build.gradle 加入

allprojects {
    repositories {
        。。。
        maven { url 'https://jitpack.io' }
    }
}

 

然後 implementation

implementation 'com.github.WillysFish:CustomControlsCamera:1.0.0'

 

 

 

參考資料:

https://github.com/android/camera-samples/tree/master

 

 

arrow
arrow

    顏澤偉 發表在 痞客邦 留言(0) 人氣()