我正在尝试实现一个拍照应用程序,我不需要完整的图片,我需要裁剪主图片的三张图片(用矩形表示),并保存它们以供以后处理。我使用的是 A4 纸张长宽比 (1:1.414)
@Composable
private fun CameraScreenContent(
viewModel: ScanLabelViewModel,
navController: NavController,
){
Box(
contentAlignment = Alignment.BottomCenter,
modifier = Modifier
.fillMaxSize()
.background(Black)
) {
val lifecycleOwner = LocalLifecycleOwner.current
val context = LocalContext.current
val cameraController: LifecycleCameraController = remember { LifecycleCameraController(context) }
val previewView = remember { PreviewView(context) }
val capturedImage = viewModel.capturedImage.collectAsState()
AndroidView(
modifier = Modifier
.align(Alignment.TopCenter)
.aspectRatio(1 / 1.414f)
.fillMaxSize()
.border(8.dp, Color(0x4A000000))
,
factory = {
previewView.apply {
setupCamera(
cameraController = cameraController,
lifecycleOwner = lifecycleOwner,
previewView = previewView,
)
}
}
)
Canvas(
modifier = Modifier
.align(Alignment.TopCenter)
.aspectRatio(1 / 1.414f)
.fillMaxSize()
) {
viewModel.setCropsMesurements(size)
//expediteur box
drawRect(
color = White,
topLeft = Offset(size.width*6/24, size.height*3/29),
size = Size((size.width/24)*11,(size.height/29)*4),
style = Stroke(4f, pathEffect = PathEffect.dashPathEffect(floatArrayOf(10f,10f),0f))
)
//destinataire box
drawRect(
color = White,
topLeft = Offset(size.width*1/24, size.height*7/29),
size = Size((size.width/24)*9,(size.height/29)*4),
style = Stroke(4f, pathEffect = PathEffect.dashPathEffect(floatArrayOf(10f,10f),0f))
)
//desciption box
drawRect(
color = White,
topLeft = Offset(size.width*1/24, size.height*17/29),
size = Size((size.width/24)*13,(size.height/29)*1),
style = Stroke(4f, pathEffect = PathEffect.dashPathEffect(floatArrayOf(10f,10f),0f))
)
}
Button(
modifier = Modifier
.padding(bottom = 32.dp)
.align(Alignment.BottomCenter),
shape = RoundedCornerShape(20.dp),
colors = ButtonDefaults.buttonColors(
contentColor = White
),
border = BorderStroke(2.dp, Color(0x4DFFFFFF)),
onClick = {
viewModel.captureImage(cameraController)
if (capturedImage.value != null){
viewModel.cropExpediteurImage()
}
}
){
Text(text = "take picture",modifier = Modifier.padding(1.dp))
}
}
}
private fun setupCamera(
cameraController: LifecycleCameraController,
lifecycleOwner: LifecycleOwner,
previewView: PreviewView,
) {
cameraController.bindToLifecycle(lifecycleOwner)
previewView.controller = cameraController
}
这是捕获图像功能
fun captureImage(
cameraController: LifecycleCameraController,
onImageCaptured: (File) -> Unit
) {
val file = File(context.cacheDir, "${UUID.randomUUID()}.jpg")
val outputOptions = ImageCapture.OutputFileOptions.Builder(file).build()
cameraController.takePicture(
outputOptions,
ContextCompat.getMainExecutor(context),
object : ImageCapture.OnImageSavedCallback {
override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
onImageCaptured(file)
}
override fun onError(exception: ImageCaptureException) {
println("Failed $exception")
}
}
)
}
我在这里尝试了很多建议的解决方案,但比例从来都不正确,我总是得到图片的小块,就像我裁剪预览而不是捕获的图像。