Created
May 16, 2020 08:19
-
-
Save kongkip/a684808747141fd5d86c035e359329eb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private fun startCamera() { | |
CameraX.unbindAll() | |
val previewConfig = PreviewConfig.Builder().apply { | |
setTargetResolution(Size(1920, 1080)) | |
setTargetRotation(viewFinder.display.rotation) | |
}.build() | |
// Build the viewFinder use case | |
val preview = Preview(previewConfig) | |
// Recompute layout every time viewFinder is updated | |
preview.setOnPreviewOutputUpdateListener { | |
val parent = viewFinder.parent as ViewGroup | |
parent.removeView(viewFinder) | |
parent.addView(viewFinder, 0) | |
viewFinder.surfaceTexture = it.surfaceTexture | |
updateTransform() | |
} | |
val analyzerConfig = ImageAnalysisConfig.Builder().apply { | |
setImageReaderMode( | |
ImageAnalysis.ImageReaderMode.ACQUIRE_LATEST_IMAGE | |
) | |
}.build() | |
// perform image analysis | |
val imageAnalysis = ImageAnalysis(analyzerConfig).apply { | |
setAnalyzer(executor, Classify()) | |
} | |
CameraX.bindToLifecycle(this, preview, imageAnalysis) | |
} | |
private fun updateTransform() { | |
val matrix = Matrix() | |
// calculate center of texture view | |
val centerX = viewFinder.width / 2f | |
val centerY = viewFinder.height / 2f | |
// correct the preview output | |
val rotationDegrees = when (viewFinder.display.rotation) { | |
Surface.ROTATION_0 -> 0 | |
Surface.ROTATION_90 -> 90 | |
Surface.ROTATION_180 -> 180 | |
Surface.ROTATION_270 -> 270 | |
else -> return | |
} | |
// apply transformations | |
matrix.postRotate(-rotationDegrees.toFloat(), centerX, centerY) | |
viewFinder.setTransform(matrix) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment