
Contents 非表示
実装
AndroidManifest.xml
以下を追加
<uses-feature
android:name="android.hardware.camera"
android:required="false" />
<uses-permission android:name="android.permission.CAMERA" />
build.gradle.kts (モジュール)
以下を追加、syncする。
implementation("io.coil-kt:coil-compose:1.4.0")
MainActivity.kt
@Composable
private fun MyCameraView() {
var imageUri by remember { mutableStateOf<Uri?>(null) }
val context = LocalContext.current
val launcher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.TakePicturePreview(),
onResult = { bitmap ->
if (bitmap != null) {
// bitmapをUriに変換
imageUri = Uri.parse(MediaStore.Images.Media.insertImage(context.contentResolver, bitmap, "Title", null))
}
}
)
val permissionLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.RequestPermission(),
onResult = { isGranted ->
if (isGranted) {
launcher.launch(null)
} else {
Log.d("CAMERA PERMISSION", "Denied")
}
}
)
Box(
modifier = Modifier.fillMaxSize(),
Alignment.Center
) {
Column(
modifier = Modifier
.padding(12.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
imageUri.let { uri ->
Image(
painter = rememberImagePainter(data = uri),
contentDescription = "Taken Photo",
modifier = Modifier
.width(320.dp)
.height(320.dp),
contentScale = ContentScale.Crop
)
}
Spacer(modifier = Modifier.padding(12.dp))
Button(
onClick = {
// カメラ許可ステータスによって処理を分岐
if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
launcher.launch(null)
} else {
permissionLauncher.launch(Manifest.permission.CAMERA)
}
},
modifier = Modifier
.width(320.dp)
.height(60.dp)
) {
Text(text = "Open Camera")
}
}
}
}