在Android中,PreviewView
是一個用于預覽相機捕獲的圖像和視頻的視圖。要在應用中使用 PreviewView
,你需要遵循以下步驟:
在你的項目的 build.gradle
文件中,添加以下依賴項:
dependencies {
implementation 'androidx.camera:camera-core:1.0.0'
implementation 'androidx.camera:camera-預覽:1.0.0'
implementation 'androidx.camera:camera-view:1.0.0'
}
在你的應用的布局文件(例如 activity_main.xml
)中,添加一個 PreviewView
控件:
<androidx.camera.core.PreviewView
android:id="@+id/previewView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
在你的 Activity 或 Fragment 中,配置相機源和預覽。首先,獲取 PreviewView
的引用,然后創建一個 CameraProvider
實例。接下來,為 PreviewView
設置一個預覽回調,以便在捕獲圖像時顯示預覽。
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import androidx.camera.core.*
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.ImageProxy
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
class MainActivity : AppCompatActivity() {
private lateinit var previewView: PreviewView
private lateinit var cameraProviderFuture: ProcessCameraProvider
private lateinit var cameraProvider: ProcessCameraProvider
private lateinit var imageAnalyzer: ImageAnalyzer
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
previewView = findViewById(R.id.previewView)
// 檢查相機權限
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CAMERA), REQUEST_CAMERA_PERMISSION)
return
}
// 創建一個單線程的 ExecutorService 用于運行相機操作
val cameraExecutor = Executors.newSingleThreadExecutor()
// 獲取 CameraProvider
cameraProviderFuture = ProcessCameraProvider.getInstance(this, cameraExecutor)
// 創建一個 ImageAnalyzer
imageAnalyzer = ImageAnalyzer()
// 設置預覽回調
previewView.setSurfaceProvider(previewView.surfaceProvider)
cameraProviderFuture.addListener({
cameraProvider = cameraProviderFuture.get()
bindPreviewView()
}, ContextCompat.getMainExecutor(this))
}
private fun bindPreviewView() {
cameraProvider.unbindAll()
val preview = Preview.Builder().build().also {
it.setSurfaceProvider(previewView.surfaceProvider)
}
val cameraSelector = CameraSelector.Builder().requireLensFacing(CameraSelector.LENS_FACING_BACK).build()
try {
cameraProvider.bindToLifecycle(this, cameraSelector, preview, imageAnalyzer)
} catch (exc: Exception) {
// 處理異常
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == REQUEST_CAMERA_PERMISSION && grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// 相機權限被授予,重新嘗試綁定預覽視圖
bindPreviewView()
}
}
companion object {
private const val REQUEST_CAMERA_PERMISSION = 1
}
}
創建一個繼承自 ImageAnalysis
的類,用于分析捕獲的圖像。在這個類中,你可以使用 ImageProxy
對象來處理圖像數據。
import android.renderscript.Allocation
import android.renderscript.Element
import android.renderscript.RenderScript
import androidx.camera.core.ImageProxy
import java.nio.ByteBuffer
class ImageAnalyzer : ImageAnalysis {
private lateinit var rs: RenderScript
private lateinit var inAllocation: Allocation
private lateinit var outAllocation: Allocation
override fun createImageAnalyzer(context: Context): ImageAnalyzer {
rs = RenderScript.create(context)
inAllocation = Allocation.createFromBitmap(rs, BitmapFactory.decodeResource(context.resources, R.drawable.ic_launcher_background))
outAllocation = Allocation.createTyped(rs, Element.U8_4(rs))
return this
}
override fun analyze(imageProxy: ImageProxy) {
val buffer = imageProxy.image?.planes?.firstOrNull()?.buffer
val byteArray = ByteArray(buffer?.capacity() ?: 0)
buffer?.get(byteArray)
// 處理圖像數據,例如識別物體、人臉等
imageProxy.close()
}
override fun close() {
inAllocation.destroy()
outAllocation.destroy()
rs.destroy()
}
}
現在,當你運行應用時,你應該能夠看到一個預覽窗口,實時顯示相機捕獲的圖像和視頻。你可以根據需要對 ImageAnalyzer
類進行擴展,以實現更高級的圖像處理功能。